Merge pull request #9 from brc0x1/master

Open Source Tripwire 2.4.3.1
This commit is contained in:
Brian Cox 2016-04-23 19:12:41 -07:00
commit acf7bd3fee
415 changed files with 29341 additions and 28693 deletions

2
.gitignore vendored
View File

@ -17,8 +17,10 @@ lib/
**/tripwire
**/twadmin
**/twprint
**/twtest
**/siggen.exe
**/tripwire.exe
**/twadmin.exe
**/twprint.exe
**/twtest.exe
releases/

View File

@ -1,3 +1,11 @@
2016-04-20 Brian Cox <bcox@tripwire.com>
* Bump version to 2.4.3.1
* Revive old 'twtest' unit test suite (such as it is); move _t.cpp files into twtest dir.
* Fix -Wnarrowing warnings in yyparse.cpp - GCC 6 would treat these as errors.
* Build with -Wextra to enable more warnings.
* Fix a variety of other compiler warnings, some exposed by -Wextra, others preexisting.
* Replace remaining tabs w/ 4 spaces. Mixing the 2 styles can now cause GCC 6 'misleading indentation' warnings.
2016-04-11 Brian Cox <bcox@tripwire.com>
* Bump version to 2.4.3.0
* Compilation fixes for gcc 4.7+ and LLVM/clang

View File

@ -1,4 +1,4 @@
What's new in Open Source Tripwire 2.4.3.0:
What's new in Open Source Tripwire 2.4.3:
* This update fixes compilation errors on modern compilers (GCC 4.7+ and LLVM/clang),
as well as some additional errors encountered on various platforms. This is intended
@ -39,6 +39,7 @@ Linuxes
- Raspbian 7 (wheezy) (armv6l) + gcc 4.6.3
- openSuSE Tumbleweed (20160408) (i586) + gcc 5.3.1
- RHEL 6.0 (powerpc64) + gcc 4.4.4
- Fedora 24 Alpha 7 (amd64) + gcc 6.0.0
OSX
- Mac OS X 10.11 + LLVM 7.0.2 / clang-700.1.81
@ -90,7 +91,7 @@ may be desirable elsewhere. It's simplest to add these to configure.in and run
autoreconf -i instead of hand-editing each Makefile individually.
* Older versions of Open Source Tripwire reportedly do not build on Tru64 UNIX.
This is likely to be true with 2.4.3.0 as well, due to the lack of appropriate
This is likely to be true with 2.4.3 as well, due to the lack of appropriate
hardware to test it on. If anyone out there has a Tru64 box and wants to fix
this, patches are always welcome.

5
configure vendored
View File

@ -3107,7 +3107,7 @@ fi
# Define the identity of the package.
PACKAGE=tripwire
VERSION=2.4.3.0
VERSION=2.4.3.1
cat >>confdefs.h <<_ACEOF
@ -6682,7 +6682,7 @@ fi
ac_config_files="$ac_config_files Makefile man/Makefile man/man4/Makefile man/man5/Makefile man/man8/Makefile src/Makefile src/cryptlib/Makefile src/core/Makefile src/db/Makefile src/fco/Makefile src/fs/Makefile src/tw/Makefile src/twcrypto/Makefile src/twparser/Makefile src/util/Makefile src/twprint/Makefile src/twadmin/Makefile src/siggen/Makefile src/tripwire/Makefile"
ac_config_files="$ac_config_files Makefile man/Makefile man/man4/Makefile man/man5/Makefile man/man8/Makefile src/Makefile src/cryptlib/Makefile src/core/Makefile src/db/Makefile src/fco/Makefile src/fs/Makefile src/tw/Makefile src/twcrypto/Makefile src/twparser/Makefile src/util/Makefile src/twprint/Makefile src/twadmin/Makefile src/siggen/Makefile src/tripwire/Makefile src/twtest/Makefile"
cat >confcache <<\_ACEOF
# This file is a shell script that caches the results of configure
@ -7418,6 +7418,7 @@ do
"src/twadmin/Makefile") CONFIG_FILES="$CONFIG_FILES src/twadmin/Makefile" ;;
"src/siggen/Makefile") CONFIG_FILES="$CONFIG_FILES src/siggen/Makefile" ;;
"src/tripwire/Makefile") CONFIG_FILES="$CONFIG_FILES src/tripwire/Makefile" ;;
"src/twtest/Makefile") CONFIG_FILES="$CONFIG_FILES src/twtest/Makefile" ;;
*) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
esac

View File

@ -5,7 +5,7 @@ dnl
AC_INIT
AC_CONFIG_SRCDIR([src/tw/tw.cpp])
AC_CANONICAL_TARGET([])
AM_INIT_AUTOMAKE(tripwire, 2.4.3.0)
AM_INIT_AUTOMAKE(tripwire, 2.4.3.1)
AM_CONFIG_HEADER(config.h)
dnl #################################
@ -431,5 +431,6 @@ src/twprint/Makefile
src/twadmin/Makefile
src/siggen/Makefile
src/tripwire/Makefile
src/twtest/Makefile
])
AC_OUTPUT

View File

@ -5,7 +5,7 @@
set -e
PRODUCT=tripwire
VERSION=2.4.3.0
VERSION=2.4.3.1
platform() {
case `uname` in

View File

@ -605,6 +605,12 @@ for i in $loosefiles; do
fi
done
#Make extra sure we don't install the unit test binary to sbin
if [ -e "$TWBIN/twtest" ] ; then
rm -f "$TWBIN/twtest"
fi
##=======================================================
## Files are now present on user's system.
## Begin Tripwire configuration.

View File

@ -1,2 +1,3 @@
SUBDIRS = cryptlib core db fco fs tw twcrypto twparser util
SUBDIRS+= twprint twadmin siggen tripwire
SUBDIRS+= twprint twadmin siggen tripwire twtest

View File

@ -160,7 +160,7 @@ target_alias = @target_alias@
target_cpu = @target_cpu@
target_os = @target_os@
target_vendor = @target_vendor@
SUBDIRS = cryptlib core db fco fs tw twcrypto twparser util twprint twadmin siggen tripwire
SUBDIRS = cryptlib core db fco fs tw twcrypto twparser util twprint twadmin siggen tripwire twtest
all: all-recursive
.SUFFIXES:

View File

@ -5,7 +5,7 @@ INCLUDES = -I..
noinst_LIBRARIES = libcore.a
libcore_a_SOURCES = \
file_unix.cpp unixfsservices.cpp \
charutil_t.cpp displayencoder_t.cpp archive.cpp charutil.cpp \
archive.cpp charutil.cpp \
cmdlineparser.cpp codeconvert.cpp core.cpp coreerrors.cpp \
corestrings.cpp crc32.cpp debug.cpp displayencoder.cpp \
displayutil.cpp error.cpp errorbucketimpl.cpp errortable.cpp \

View File

@ -52,7 +52,6 @@ AR = ar
ARFLAGS = cru
libcore_a_AR = $(AR) $(ARFLAGS)
am_libcore_a_OBJECTS = file_unix.$(OBJEXT) unixfsservices.$(OBJEXT) \
charutil_t.$(OBJEXT) displayencoder_t.$(OBJEXT) \
archive.$(OBJEXT) charutil.$(OBJEXT) cmdlineparser.$(OBJEXT) \
codeconvert.$(OBJEXT) core.$(OBJEXT) coreerrors.$(OBJEXT) \
corestrings.$(OBJEXT) crc32.$(OBJEXT) debug.$(OBJEXT) \
@ -193,7 +192,7 @@ INCLUDES = -I..
noinst_LIBRARIES = libcore.a
libcore_a_SOURCES = \
file_unix.cpp unixfsservices.cpp \
charutil_t.cpp displayencoder_t.cpp archive.cpp charutil.cpp \
archive.cpp charutil.cpp \
cmdlineparser.cpp codeconvert.cpp core.cpp coreerrors.cpp \
corestrings.cpp crc32.cpp debug.cpp displayencoder.cpp \
displayutil.cpp error.cpp errorbucketimpl.cpp errortable.cpp \

316
src/core/archive.cpp Executable file → Normal file
View File

@ -32,10 +32,10 @@
///////////////////////////////////////////////////////////////////////////////
// archive.cpp -- classes that abstract a raw byte archive
//
// cArchive -- interface for single-direction (one pass) reads and writes
// cBidirArchive -- interface for a random-access archive
// cMemArchive -- implementation of a bidirectional archive in memory
// cFileArchive -- implementation of a bidirectional archive as a file
// cArchive -- interface for single-direction (one pass) reads and writes
// cBidirArchive -- interface for a random-access archive
// cMemArchive -- implementation of a bidirectional archive in memory
// cFileArchive -- implementation of a bidirectional archive as a file
#include "stdcore.h"
#include "archive.h"
@ -219,34 +219,34 @@ void cArchive::WriteBlob(const void* pBlob, int count) // throw(eArchive)
int32 cArchive::GetStorageSize(const TSTRING& str)
{
int32 size = sizeof(int32); // the length is always stored
//
// after the length, all of the characters in the string are written as 16-bit values,
// except for the null character
//
size += ( str.length() * 2 );
int32 size = sizeof(int32); // the length is always stored
//
// after the length, all of the characters in the string are written as 16-bit values,
// except for the null character
//
size += ( str.length() * 2 );
return size;
return size;
}
int64 cArchive::Copy(cArchive* pFrom, int64 amt)
{
enum { BUF_SIZE = 2048 };
int8 buf[BUF_SIZE];
int64 amtLeft = amt;
enum { BUF_SIZE = 2048 };
int8 buf[BUF_SIZE];
int64 amtLeft = amt;
while(amtLeft > 0)
{
int64 amtToRead = amtLeft > (int64)BUF_SIZE ? (int64)BUF_SIZE : amtLeft;
int64 amtRead = pFrom->ReadBlob(buf, static_cast<int>( amtToRead ) );
amtLeft -= amtRead;
WriteBlob(buf, static_cast<int>( amtRead ) );
if(amtRead < amtToRead)
break;
}
while(amtLeft > 0)
{
int64 amtToRead = amtLeft > (int64)BUF_SIZE ? (int64)BUF_SIZE : amtLeft;
int64 amtRead = pFrom->ReadBlob(buf, static_cast<int>( amtToRead ) );
amtLeft -= amtRead;
WriteBlob(buf, static_cast<int>( amtRead ) );
if(amtRead < amtToRead)
break;
}
// return the amount copied ...
return (amt - amtLeft);
// return the amount copied ...
return (amt - amtLeft);
}
///////////////////////////////////////////////////////////////////////////////
@ -429,7 +429,7 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive)
if (len > mAllocatedLen)
{
// grow the buffer
// only error if we are in debug mode
// only error if we are in debug mode
#ifdef _DEBUG
if (len > mMaxAllocatedLen)
ThrowAndAssert(eArchiveOutOfMem());
@ -486,9 +486,9 @@ class cFixedMemArchive : public cBidirArchive
{
public:
int8* mpMemory;
int32 mSize;
int32 mReadHead;
int8* mpMemory;
int32 mSize;
int32 mReadHead;
};
*/
@ -496,18 +496,18 @@ public:
// cFixedMemArchive
//-----------------------------------------------------------------------------
cFixedMemArchive::cFixedMemArchive()
: mpMemory (0),
mSize (0),
mReadHead (0)
: mpMemory (0),
mSize (0),
mReadHead (0)
{
}
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()
@ -516,9 +516,9 @@ cFixedMemArchive::~cFixedMemArchive()
void cFixedMemArchive::Attach( int8* pMem, int32 size )
{
mpMemory = pMem;
mSize = size;
mReadHead = 0;
mpMemory = pMem;
mSize = size;
mReadHead = 0;
}
void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive)
@ -545,28 +545,28 @@ void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive)
int64 cFixedMemArchive::CurrentPos() const
{
return mReadHead;
return mReadHead;
}
int64 cFixedMemArchive::Length() const
{
return mSize;
return mSize;
}
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)
{
count = static_cast<int>( mSize - mReadHead );
if (count <= 0)
return 0;
}
{
count = static_cast<int>( mSize - mReadHead );
if (count <= 0)
return 0;
}
if (pDest != 0)
memcpy(pDest, mpMemory + mReadHead, count);
@ -576,12 +576,12 @@ int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive)
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)
{
ASSERT( false );
throw eArchiveWrite();
ASSERT( false );
throw eArchiveWrite();
}
memcpy(mpMemory + mReadHead, pDest, count);
@ -598,9 +598,9 @@ int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive)
//Ctor -- Initialize member variables to 0 or NULL equivalents.
cFileArchive::cFileArchive() :
mFileSize(0),
mReadHead(0),
isWritable(false)
mFileSize(0),
mReadHead(0),
isWritable(false)
{}
cFileArchive::~cFileArchive()
@ -609,7 +609,7 @@ cFileArchive::~cFileArchive()
bool cFileArchive::EndOfFile()
{
return ( mReadHead >= mFileSize );
return ( mReadHead >= mFileSize );
}
////////////////////////////////////////////////////////////////////////
@ -618,38 +618,38 @@ bool cFileArchive::EndOfFile()
/////////////////////////////////////////////////////////////////////////
void cFileArchive::Seek( int64 offset, SeekFrom from) // throw(eArchive)
{
try
{
switch (from)
{
case cBidirArchive::BEGINNING:
break;
case cBidirArchive::CURRENT:
offset = mReadHead + offset;
break;
case cBidirArchive::END:
offset = mFileSize + offset;
break;
default:
throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ;
}
try
{
switch (from)
{
case cBidirArchive::BEGINNING:
break;
case cBidirArchive::CURRENT:
offset = mReadHead + offset;
break;
case cBidirArchive::END:
offset = mFileSize + offset;
break;
default:
throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ;
}
if ( offset > mFileSize )
throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ;
mReadHead = offset;
if ( offset > mFileSize )
throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ;
mReadHead = offset;
mCurrentFile.Seek(mReadHead, cFile::SEEK_BEGIN);
//This is where the actual read/writehead is set!!
}//try
catch( eFile& fileError )
{
throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) );
}
mCurrentFile.Seek(mReadHead, cFile::SEEK_BEGIN);
//This is where the actual read/writehead is set!!
}//try
catch( eFile& fileError )
{
throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) );
}
}
int64 cFileArchive::CurrentPos(void) const
{
return mReadHead;
return mReadHead;
}
/////////////////////////////////////////////////////////////////////////
@ -657,14 +657,14 @@ int64 cFileArchive::CurrentPos(void) const
/////////////////////////////////////////////////////////////////////////
int64 cFileArchive::Length(void) const
{
try
{
return mCurrentFile.GetSize();
}
catch(eFile& fileError)
{
throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) );
}
try
{
return mCurrentFile.GetSize();
}
catch(eFile& fileError)
{
throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) );
}
}
/////////////////////////////////////////////////////////////////////////
@ -672,25 +672,25 @@ int64 cFileArchive::Length(void) const
/////////////////////////////////////////////////////////////////////////
void cFileArchive::OpenRead(const TCHAR* filename, uint32 openFlags)
{
try
{
try
{
// set up open flags
uint32 flags = cFile::OPEN_READ;
flags |= ( ( openFlags & FA_OPEN_TRUNCATE ) ? cFile::OPEN_TRUNCATE : 0 );
flags |= ( ( openFlags & FA_OPEN_TEXT ) ? cFile::OPEN_TEXT : 0 );
flags |= ( ( openFlags & FA_NONBLOCKING ) ? cFile::OPEN_NONBLOCKING :0 );
mCurrentFilename = filename;
mCurrentFile.Open( filename, flags );
isWritable = false;
mCurrentFilename = filename;
mCurrentFile.Open( filename, flags );
isWritable = false;
mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN );
}
catch(eFile& fileError)
{
throw(eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) );
}
mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN );
}
catch(eFile& fileError)
{
throw(eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) );
}
}
/////////////////////////////////////////////////////////////////////////
@ -698,34 +698,34 @@ void cFileArchive::OpenRead(const TCHAR* filename, uint32 openFlags)
/////////////////////////////////////////////////////////////////////////
void cFileArchive::OpenReadWrite(const TCHAR* filename, uint32 openFlags)
{
try
{
try
{
// set up open flags
uint32 flags = cFile::OPEN_WRITE;
flags |= ( ( openFlags & FA_OPEN_TRUNCATE ) ? cFile::OPEN_TRUNCATE : 0 );
flags |= ( ( openFlags & FA_OPEN_TEXT ) ? cFile::OPEN_TEXT : 0 );
flags |= ( ( openFlags & FA_NONBLOCKING ) ? cFile::OPEN_NONBLOCKING :0 );
mCurrentFilename = filename;
mCurrentFile.Open( filename, flags );
isWritable = true;
mCurrentFilename = filename;
mCurrentFile.Open( filename, flags );
isWritable = true;
mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN );
}
catch(eFile& fileError)
{
throw( eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) );
}
mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN );
}
catch(eFile& fileError)
{
throw( eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) );
}
}
/////////////////////////////////////////////////////////////////////////
// GetCurrentFilename -- Returns the name of the file currently associated
// with the FileArchive.
// with the FileArchive.
/////////////////////////////////////////////////////////////////////////
TSTRING cFileArchive::GetCurrentFilename(void) const
{
return mCurrentFilename;
return mCurrentFilename;
}
/////////////////////////////////////////////////////////////////////////
@ -733,18 +733,18 @@ TSTRING cFileArchive::GetCurrentFilename(void) const
/////////////////////////////////////////////////////////////////////////
void cFileArchive::Close()
{
try
try
{
mCurrentFile.Close();
mFileSize = 0;
mReadHead = 0;
mCurrentFile.Close();
mFileSize = 0;
mReadHead = 0;
mCurrentFilename = _T("");
}
catch(eFile& fileError)
{
throw( eArchive( mCurrentFilename, fileError.GetDescription() ) );
}
mCurrentFilename = _T("");
}
catch(eFile& fileError)
{
throw( eArchive( mCurrentFilename, fileError.GetDescription() ) );
}
}
/////////////////////////////////////////////////////////////////////////
@ -753,22 +753,22 @@ void cFileArchive::Close()
/////////////////////////////////////////////////////////////////////////
int cFileArchive::Read(void* pDest, int count)
{
try
try
{
if ( mReadHead + count > mFileSize )
count = static_cast<int>( mFileSize - mReadHead );
if ( mReadHead + count > mFileSize )
count = static_cast<int>( mFileSize - mReadHead );
if ( pDest != NULL )
{
int nbRead =
if ( pDest != NULL )
{
int nbRead =
static_cast<int>( mCurrentFile.Read( pDest, count ) );
// 'count' may not be equal to 'nbRead' if the file is open in
// text mode.
count = nbRead;
if(count < 0) count = 0;
}
else
if(count < 0) count = 0;
}
else
{
int i;
int32 dummy;
@ -777,20 +777,20 @@ int cFileArchive::Read(void* pDest, int count)
if (i < (int)sizeof(int32))
{
if (i > 0)
mCurrentFile.Read( &dummy, i );
mCurrentFile.Read( &dummy, i );
break;
}
mCurrentFile.Read( &dummy, i );
mCurrentFile.Read( &dummy, i );
}
}
mReadHead += count;
return count;
}
catch( eFile& fileError )
{
throw( eArchiveRead( mCurrentFilename, fileError.GetDescription() ) );
}
mReadHead += count;
return count;
}
catch( eFile& fileError )
{
throw( eArchiveRead( mCurrentFilename, fileError.GetDescription() ) );
}
}
@ -841,20 +841,20 @@ int cFileArchive::Write(const void* pDest, int count) // throw(eArchive)
/////////////////////////////////////////////////////////////////////////
void cFileArchive::Truncate() // throw(eArchive)
{
ASSERT( mCurrentFile.IsOpen() );
ASSERT( mCurrentFile.isWritable );
ASSERT( mCurrentFile.IsOpen() );
ASSERT( mCurrentFile.isWritable );
try
{
mCurrentFile.Truncate ( mReadHead );
}
catch( eFile& fileError )
{
//TODO: create an error number for truncate...
throw( eArchiveWrite( mCurrentFilename, fileError.GetDescription() ) );
}
try
{
mCurrentFile.Truncate ( mReadHead );
}
catch( eFile& fileError )
{
//TODO: create an error number for truncate...
throw( eArchiveWrite( mCurrentFilename, fileError.GetDescription() ) );
}
mFileSize = mReadHead;
mFileSize = mReadHead;
}
@ -871,8 +871,8 @@ void cLockedTemporaryFileArchive::OpenReadWrite( const TCHAR* filename, uint32 o
try {
ASSERT( !mCurrentFile.IsOpen() ); // shouldn't be able to create a new file when we're already open
if ( mCurrentFile.IsOpen() )
throw( eArchive( mCurrentFilename, _T("Internal Error") ) );
if ( mCurrentFile.IsOpen() )
throw( eArchive( mCurrentFilename, _T("Internal Error") ) );
///////////////////////////////////////////////////////////////////////////////

182
src/core/archive.h Executable file → Normal file
View File

@ -32,10 +32,10 @@
///////////////////////////////////////////////////////////////////////////////
// archive.h -- classes that abstract a raw byte archive
//
// cArchive -- interface for single-direction (one pass) reads and writes
// cBidirArchive -- interface for a random-access archive
// cMemArchive -- implementation of a bidirectional archive in memory
// cFileArchive -- implementation of a bidirectional archive as a file
// cArchive -- interface for single-direction (one pass) reads and writes
// cBidirArchive -- interface for a random-access archive
// cMemArchive -- implementation of a bidirectional archive in memory
// cFileArchive -- implementation of a bidirectional archive as a file
#ifndef __ARCHIVE_H
#define __ARCHIVE_H
@ -56,26 +56,26 @@
//=============================================================================
// eArchive exception classes
//=============================================================================
TSS_FILE_EXCEPTION( eArchive, eFileError );
TSS_FILE_EXCEPTION( eArchiveOpen, eArchive );
TSS_FILE_EXCEPTION( eArchiveWrite, eArchive );
TSS_FILE_EXCEPTION( eArchiveRead, eArchive );
TSS_FILE_EXCEPTION( eArchiveEOF, eArchive );
TSS_FILE_EXCEPTION( eArchiveSeek, eArchive );
TSS_FILE_EXCEPTION( eArchiveMemmap, eArchive );
TSS_FILE_EXCEPTION( eArchiveOutOfMem, eArchive );
TSS_FILE_EXCEPTION( eArchiveInvalidOp, eArchive );
TSS_FILE_EXCEPTION( eArchiveFormat, eArchive );
TSS_FILE_EXCEPTION( eArchive, eFileError );
TSS_FILE_EXCEPTION( eArchiveOpen, eArchive );
TSS_FILE_EXCEPTION( eArchiveWrite, eArchive );
TSS_FILE_EXCEPTION( eArchiveRead, eArchive );
TSS_FILE_EXCEPTION( eArchiveEOF, eArchive );
TSS_FILE_EXCEPTION( eArchiveSeek, eArchive );
TSS_FILE_EXCEPTION( eArchiveMemmap, eArchive );
TSS_FILE_EXCEPTION( eArchiveOutOfMem, eArchive );
TSS_FILE_EXCEPTION( eArchiveInvalidOp, eArchive );
TSS_FILE_EXCEPTION( eArchiveFormat, eArchive );
TSS_FILE_EXCEPTION( eArchiveNotRegularFile, eArchive );
TSS_BEGIN_EXCEPTION( eArchiveCrypto, eArchive )
TSS_BEGIN_EXCEPTION( eArchiveCrypto, eArchive )
virtual TSTRING GetMsg() const;
// eCryptoArchive appends a special string to the end of
// all exception messages
virtual TSTRING GetMsg() const;
// eCryptoArchive appends a special string to the end of
// all exception messages
TSS_END_EXCEPTION()
TSS_EXCEPTION( eArchiveStringTooLong, eArchive );
// throw( eArchiveOpen( cErrorUtil::MakeFileError( fileError.GetMsg(), strTempFile ) ) );
// throw( eArchiveOpen( cErrorUtil::MakeFileError( fileError.GetMsg(), strTempFile ) ) );
//=============================================================================
@ -87,7 +87,7 @@ class cArchive
public:
virtual ~cArchive() {}
// convenience methods
// convenience methods
//
// Specific Read functions throw(eArchive) if EOF is reached because
// if the caller is requesting a certain amount of data to be present,
@ -101,33 +101,33 @@ public:
// All write functions throw exceptions for unexpected events like
// running out of memory or disk space.
//
void ReadInt16(int16& ret); // throw(eArchive)
void ReadInt32(int32& ret); // throw(eArchive)
void ReadInt16(int16& ret); // throw(eArchive)
void ReadInt32(int32& ret); // throw(eArchive)
void ReadInt64(int64& ret); // throw(eArchive)
void ReadString(TSTRING& ret); // throw(eArchive)
int ReadBlob(void* pBlob, int count);
void WriteInt16(int16 i); // throw(eArchive)
void WriteInt32(int32 i); // throw(eArchive)
void WriteInt64(int64 i); // throw(eArchive)
void WriteInt16(int16 i); // throw(eArchive)
void WriteInt32(int32 i); // throw(eArchive)
void WriteInt64(int64 i); // throw(eArchive)
void WriteString(TSTRING s); // throw(eArchive)
void WriteBlob(const void* pBlob, int count); // throw(eArchive)
static int32 GetStorageSize(const TSTRING& str);
// this method calculates how many bytes the given string will take up in the archive and returns
// that value
// NOTE -- if the implementation of ReadString() or WriteString() ever changes, this method will also
// need to change.
static int32 GetStorageSize(const TSTRING& str);
// this method calculates how many bytes the given string will take up in the archive and returns
// that value
// NOTE -- if the implementation of ReadString() or WriteString() ever changes, this method will also
// need to change.
int64 Copy(cArchive* pFrom, int64 amt); // throw(eArchive)
// this method copies amt bytes from pFrom to itself, throwing an eArchive if anything goes wrong.
int64 Copy(cArchive* pFrom, int64 amt); // throw(eArchive)
// this method copies amt bytes from pFrom to itself, throwing an eArchive if anything goes wrong.
// only makes sense to call for reading archives
virtual bool EndOfFile() = 0;
protected:
// overrides
virtual int Read(void* pDest, int count) = 0;
virtual int Write(const void* pDest, int count) = 0; // throw(eArchive);
// overrides
virtual int Read(void* pDest, int count) = 0;
virtual int Write(const void* pDest, int count) = 0; // throw(eArchive);
};
///////////////////////////////////////////////////////////////////////////////
@ -202,7 +202,7 @@ public:
void Truncate(); // set the length to the current pos
int8* GetMemory() const { return mpMemory; }
int8* GetMemory() const { return mpMemory; }
protected:
int8* mpMemory;
@ -211,50 +211,50 @@ protected:
int mLogicalSize;
int mReadHead;
virtual int Read(void* pDest, int count);
virtual int Write(const void* pDest, int count); // throw(eArchive)
virtual int Read(void* pDest, int count);
virtual int Write(const void* pDest, int count); // throw(eArchive)
virtual void AllocateMemory(int len); // throw(eArchive)
};
///////////////////////////////////////////////////////////////////////////////
// cFixedMemArchive -- a memory archive that operates on a fixed-sized block of
// memory that has already been allocated
// memory that has already been allocated
///////////////////////////////////////////////////////////////////////////////
class cFixedMemArchive : public cBidirArchive
{
public:
cFixedMemArchive();
cFixedMemArchive( int8* pMem, int32 size );
virtual ~cFixedMemArchive();
cFixedMemArchive();
cFixedMemArchive( int8* pMem, int32 size );
virtual ~cFixedMemArchive();
void Attach( int8* pMem, int32 size );
// this method associates the archive with pMem and sets the size of the
// archive. Unlike cMemoryArchive, this may never grow or shrink in size.
void Attach( int8* pMem, int32 size );
// this method associates the archive with pMem and sets the size of the
// archive. Unlike cMemoryArchive, this may never grow or shrink in size.
//-----------------------------------
// cBidirArchive interface
//-----------------------------------
virtual void Seek (int64 offset, SeekFrom from) ; // throw(eArchive);
virtual int64 CurrentPos () const ;
virtual int64 Length () const ;
//-----------------------------------
// cBidirArchive interface
//-----------------------------------
virtual void Seek (int64 offset, SeekFrom from) ; // throw(eArchive);
virtual int64 CurrentPos () const ;
virtual int64 Length () const ;
virtual bool EndOfFile();
protected:
//-----------------------------------
// cArchive interface
//-----------------------------------
virtual int Read(void* pDest, int count); // throw(eArchive)
virtual int Write(const void* pDest, int count); // throw(eArchive)
//-----------------------------------
// cArchive interface
//-----------------------------------
virtual int Read(void* pDest, int count); // throw(eArchive)
virtual int Write(const void* pDest, int count); // throw(eArchive)
int8* mpMemory;
int32 mSize;
int32 mReadHead;
int8* mpMemory;
int32 mSize;
int32 mReadHead;
};
class cFileArchive : public cBidirArchive
{
public:
cFileArchive();
virtual ~cFileArchive();
cFileArchive();
virtual ~cFileArchive();
enum OpenFlags
{
@ -264,34 +264,34 @@ public:
};
// TODO: Open should throw
virtual void OpenRead(const TCHAR* filename, uint32 openFlags = 0 );
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,
// and is truncated to zero length if truncateFile is set to true;
TSTRING GetCurrentFilename(void) const;
virtual void Close(void);
virtual void OpenRead(const TCHAR* filename, uint32 openFlags = 0 );
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,
// and is truncated to zero length if truncateFile is set to true;
TSTRING GetCurrentFilename(void) const;
virtual void Close(void);
void Truncate(); // throw(eArchive) // set the length to the current pos
//-----------------------------------
// cBidirArchive interface
//-----------------------------------
virtual bool EndOfFile();
virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive)
virtual int64 CurrentPos() const;
virtual int64 Length() const;
//-----------------------------------
// cBidirArchive interface
//-----------------------------------
virtual bool EndOfFile();
virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive)
virtual int64 CurrentPos() const;
virtual int64 Length() const;
protected:
int64 mFileSize; //Size of FileArchive
int64 mReadHead; //Current position of read/write head
//-----------------------------------
// cArchive interface
//-----------------------------------
virtual int Read(void* pDest, int count);
virtual int Write(const void* pDest, int count); //throw(eArchive)
bool isWritable;
cFile mCurrentFile;
TSTRING mCurrentFilename; //current file
int64 mFileSize; //Size of FileArchive
int64 mReadHead; //Current position of read/write head
//-----------------------------------
// cArchive interface
//-----------------------------------
virtual int Read(void* pDest, int count);
virtual int Write(const void* pDest, int count); //throw(eArchive)
bool isWritable;
cFile mCurrentFile;
TSTRING mCurrentFilename; //current file
};
///////////////////////////////////////////////////////////////
@ -305,15 +305,15 @@ protected:
class cLockedTemporaryFileArchive : public cFileArchive
{
public:
virtual void OpenReadWrite ( const TCHAR* filename = NULL, uint32 openFlags = FA_OPEN_TRUNCATE );
// creates the file. filename must not exist on the file system.
virtual void OpenReadWrite ( const TCHAR* filename = NULL, uint32 openFlags = FA_OPEN_TRUNCATE );
// creates the file. filename must not exist on the file system.
// if filename is NULL, the class will create and use a temporary file.
// truncateFile has no meaning
//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
// cArchive::ERR_OPEN_FAILED)
//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
// cArchive::ERR_OPEN_FAILED)
virtual void Close();
virtual void Close();
// close and delete the file
private:
// open for read only makes no sense if we're always creating the file,

View File

@ -63,19 +63,19 @@ int util_tlen( const TCHAR* cur, size_t count )
*/
//
//
// finds the next whole character in string identified by ['cur'-'end')
// identifies beginning of char in 'first', then end of character in 'last'
// returns number of TCHARs that make up the next character
// if there are no more characters, will return 0 and first = last = end
// POSTCONDITIONS:
//
//
// RETURNS:
//
//
// THROWS:
//
//
// COMPLEXITY:
//
//
//
/* static */
@ -159,19 +159,19 @@ int cCharUtil::PeekNextChar( const TSTRING::const_iterator& cur,
// TSTRING::const_iterator& last )
//-----------------------------------------------------------------------------
// REQUIRES:
//
//
// EFFECTS:
//
//
// same as PeekNextChar but increments 'cur' to 'last'
//
// POSTCONDITIONS:
//
//
// RETURNS:
//
//
// THROWS:
//
//
// COMPLEXITY:
//
//
//
/* static */

View File

@ -39,8 +39,8 @@
// ctor, dotr
///////////////////////////////////////////////////////////////////////////////
cCmdLineParser::cCmdLineParser() :
mArgTable(HASH_VERY_SMALL),
mLastArgInfo(-1, PARAM_NONE)
mArgTable(HASH_VERY_SMALL),
mLastArgInfo(-1, PARAM_NONE)
{
}
@ -53,26 +53,26 @@ cCmdLineParser::~cCmdLineParser()
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed)
{
if(arg.empty() && alias.empty())
{
// this refers to the list of parameters that comes after all the cmd line switches
mLastArgInfo.mId = argId;
mLastArgInfo.mNumParams = numParams;
return ;
}
if(arg.empty() && alias.empty())
{
// this refers to the list of parameters that comes after all the cmd line switches
mLastArgInfo.mId = argId;
mLastArgInfo.mNumParams = numParams;
return ;
}
if(! arg.empty())
mArgTable.Insert(arg, cArgInfo(argId, numParams));
if(! alias.empty())
{
// put the alias in the table with a '-' prepended to it so it matches '--'
TSTRING str(_T("-"));
str += alias;
mArgTable.Insert(str, cArgInfo(argId, numParams));
}
// This argument can appear more than once on the command line.
if( multipleAllowed )
mMultipleAllowed.insert( argId );
if(! arg.empty())
mArgTable.Insert(arg, cArgInfo(argId, numParams));
if(! alias.empty())
{
// put the alias in the table with a '-' prepended to it so it matches '--'
TSTRING str(_T("-"));
str += alias;
mArgTable.Insert(str, cArgInfo(argId, numParams));
}
// This argument can appear more than once on the command line.
if( multipleAllowed )
mMultipleAllowed.insert( argId );
}
///////////////////////////////////////////////////////////////////////////////
@ -80,11 +80,11 @@ void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias,
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::Clear()
{
mLastArgInfo.mId = -1;
mLastArgInfo.mNumParams = PARAM_INVALID;
mArgTable.Clear();
mArgData.clear();
mMutExList.clear();
mLastArgInfo.mId = -1;
mLastArgInfo.mNumParams = PARAM_INVALID;
mArgTable.Clear();
mArgData.clear();
mMutExList.clear();
}
///////////////////////////////////////////////////////////////////////////////
@ -92,54 +92,54 @@ void cCmdLineParser::Clear()
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
{
// clear out any existing data
mArgData.clear();
// clear out any existing data
mArgData.clear();
const TCHAR* pCurArg = 0;
bool bProcessedFinalParams = false; // gets set to true when the parameters to the command line are processed
const TCHAR* pCurArg = 0;
bool bProcessedFinalParams = false; // gets set to true when the parameters to the command line are processed
// I assume argv[0] is the executable name...
for(int i=1; i < argc; i++)
{
if(argv[i][0] == _T('-'))
{
pCurArg = argv[i];
// I assume argv[0] is the executable name...
for(int i=1; i < argc; i++)
{
if(argv[i][0] == _T('-'))
{
pCurArg = argv[i];
// this is a switch; find it in the table...
cArgInfo argInfo;
if ( !mArgTable.Lookup( TSTRING(&argv[i][1] ), argInfo ) )
{
// unknown switch!
throw eCmdLineInvalidArg(
// this is a switch; find it in the table...
cArgInfo argInfo;
if ( !mArgTable.Lookup( TSTRING(&argv[i][1] ), argInfo ) )
{
// unknown switch!
throw eCmdLineInvalidArg(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
}
//
// make sure this hasn't been specified yet...
//
if( ArgInList( argInfo.mId ) )
{
// Make sure it isn't okay for this one to appear more than once...
std::set<int>::iterator it = mMultipleAllowed.find( argInfo.mId );
if( it == mMultipleAllowed.end() )
{
// It wasn't in our list of allowed params, so error.
throw eCmdLineMultiArg(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ argv[i] );
}
}
//
// add it to the list..
//
mArgData.push_back(cArgData(argInfo.mId, TSTRING(argv[i])));
cArgData& curArg = mArgData.back();
switch( argInfo.mNumParams )
{
case PARAM_NONE:
// make sure there are no parameters to this, but be careful because
}
//
// make sure this hasn't been specified yet...
//
if( ArgInList( argInfo.mId ) )
{
// Make sure it isn't okay for this one to appear more than once...
std::set<int>::iterator it = mMultipleAllowed.find( argInfo.mId );
if( it == mMultipleAllowed.end() )
{
// It wasn't in our list of allowed params, so error.
throw eCmdLineMultiArg(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ argv[i] );
}
}
//
// add it to the list..
//
mArgData.push_back(cArgData(argInfo.mId, TSTRING(argv[i])));
cArgData& curArg = mArgData.back();
switch( argInfo.mNumParams )
{
case PARAM_NONE:
// make sure there are no parameters to this, but be careful because
// 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
// TODO: In the future we may want to support a '--' switch that specifies the start
@ -147,121 +147,121 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
for (int j = i + 2; j < argc; ++j )
{
if (argv[j][0] == _T('-'))
{
// >0 parameter passed !
throw eCmdLineBadParam(
{
// >0 parameter passed !
throw eCmdLineBadParam(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
}
}
}
}
break;
case PARAM_ONE:
// get the next parameter...
i++;
if ( (i >= argc) || (argv[i][0] == _T('-')) )
{
// zero parameters passed to something that needed one param
throw eCmdLineBadParam(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
}
curArg.mParams.push_back( TSTRING(argv[i]) );
break;
case PARAM_MANY:
i++;
while((i < argc) && (argv[i][0] != _T('-')))
{
curArg.mParams.push_back(TSTRING(argv[i]));
i++;
}
i--; // since we have gone too far at this point
break;
case PARAM_ONE:
// get the next parameter...
i++;
if ( (i >= argc) || (argv[i][0] == _T('-')) )
{
// zero parameters passed to something that needed one param
throw eCmdLineBadParam(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
}
curArg.mParams.push_back( TSTRING(argv[i]) );
break;
case PARAM_MANY:
i++;
while((i < argc) && (argv[i][0] != _T('-')))
{
curArg.mParams.push_back(TSTRING(argv[i]));
i++;
}
i--; // since we have gone too far at this point
break;
default:
ASSERTMSG( false, "Unknown number of arguments to parser" );
}
}
else
{
bProcessedFinalParams = true;
// this must be the final "unnamed" arg
// first, make sure it is consistent with the current info...
bool bResult = true;
switch(mLastArgInfo.mNumParams)
{
case PARAM_NONE:
// this is an error; they didn't want any command line parameters...
bResult = false;
break;
case PARAM_ONE:
if(i+1 != argc)
// there is >1 final parameter; it is an error
bResult = false;
break;
case PARAM_MANY:
// we'll catch errors below
break;
default:
ASSERT(false);
}
if(! bResult)
{
throw eCmdLineBadParam( );
}
ASSERTMSG( false, "Unknown number of arguments to parser" );
}
}
else
{
bProcessedFinalParams = true;
// this must be the final "unnamed" arg
// first, make sure it is consistent with the current info...
bool bResult = true;
switch(mLastArgInfo.mNumParams)
{
case PARAM_NONE:
// this is an error; they didn't want any command line parameters...
bResult = false;
break;
case PARAM_ONE:
if(i+1 != argc)
// there is >1 final parameter; it is an error
bResult = false;
break;
case PARAM_MANY:
// we'll catch errors below
break;
default:
ASSERT(false);
}
if(! bResult)
{
throw eCmdLineBadParam( );
}
// ok, we can push the final parameter info onto the list...
mArgData.push_back(cArgData(mLastArgInfo.mId));
cArgData& curArg = mArgData.back();
while ( i < argc )
{
if ( argv[i][0] == _T('-') )
{
if ( ! pCurArg )
{
throw eCmdLineBadSwitchPos(
// ok, we can push the final parameter info onto the list...
mArgData.push_back(cArgData(mLastArgInfo.mId));
cArgData& curArg = mArgData.back();
while ( i < argc )
{
if ( argv[i][0] == _T('-') )
{
if ( ! pCurArg )
{
throw eCmdLineBadSwitchPos(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ argv[i] );
}
else
{
// there was an extra parameter passed somewhere!
throw eCmdLineBadArgParam(
}
else
{
// there was an extra parameter passed somewhere!
throw eCmdLineBadArgParam(
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
}
}
}
}
// add this param to the list
curArg.mParams.push_back(TSTRING(argv[i]));
i++;
}
}
// add this param to the list
curArg.mParams.push_back(TSTRING(argv[i]));
i++;
}
}
}
}
// 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
// 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
if(! bProcessedFinalParams)
{
if(mLastArgInfo.mNumParams == PARAM_ONE)
{
throw eCmdLineBadParam( );
}
}
// 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
// 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
if(! bProcessedFinalParams)
{
if(mLastArgInfo.mNumParams == PARAM_ONE)
{
throw eCmdLineBadParam( );
}
}
// Check for "relationship errors":
TestMutEx();
TestDependency();
// Check for "relationship errors":
TestMutEx();
TestDependency();
}
///////////////////////////////////////////////////////////////////////////////
@ -269,27 +269,27 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::TestMutEx()
{
std::list<std::pair<int,int> >::const_iterator i;
cCmdLineIter iter1(*this), iter2(*this);
for(i = mMutExList.begin(); i != mMutExList.end(); i++)
{
//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
// deal to do it this way.
iter1.SeekToArg(i->first);
if(! iter1.Done())
{
iter2.SeekToArg(i->second);
if(! iter2.Done())
{
// we have a mutual exclusion violation!
throw eCmdLineMutEx(
std::list<std::pair<int,int> >::const_iterator i;
cCmdLineIter iter1(*this), iter2(*this);
for(i = mMutExList.begin(); i != mMutExList.end(); i++)
{
//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
// deal to do it this way.
iter1.SeekToArg(i->first);
if(! iter1.Done())
{
iter2.SeekToArg(i->second);
if(! iter2.Done())
{
// we have a mutual exclusion violation!
throw eCmdLineMutEx(
iter1.ActualParam()
+ _T(", ")
+ iter2.ActualParam() );
}
}
}
}
}
}
}
@ -298,55 +298,55 @@ void cCmdLineParser::TestMutEx()
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::TestDependency()
{
std::list< std::pair< std::pair< int, int>, bool > >::const_iterator i;
cCmdLineIter iter1(*this), iter2(*this);
std::list< std::pair< std::pair< int, int>, bool > >::const_iterator i;
cCmdLineIter iter1(*this), iter2(*this);
for( i = mDependencyList.begin(); i != mDependencyList.end(); ++i)
{
iter1.SeekToArg( i->first.first );
// was it on the command line?
if( !iter1.Done() )
{
// it was, is the corresponding arg on the command line?
iter2.SeekToArg( i->first.second );
if( iter2.Done() ) // it wasn't, dependency error
{
TSTRING arg1, arg2, alias1, alias2;
cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 );
cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 );
for( i = mDependencyList.begin(); i != mDependencyList.end(); ++i)
{
iter1.SeekToArg( i->first.first );
// was it on the command line?
if( !iter1.Done() )
{
// it was, is the corresponding arg on the command line?
iter2.SeekToArg( i->first.second );
if( iter2.Done() ) // it wasn't, dependency error
{
TSTRING arg1, arg2, alias1, alias2;
cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 );
cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 );
// determine in which form the user passed the arguments,
// and construct the error message in the same form
if ( iter1.ActualParam().length() == 2 )
throw eCmdLineDependency( _T("The switch -") + arg1 + _T(" requires -") + arg2 +_T(".") );
else
throw eCmdLineDependency( _T("The switch --") + alias1 + _T(" requires --") + alias2 + _T(".") );
}
}
else if( i->second )
// only make this second check if the dependencies are MUTUAL,
// as indicated (or not) by the bool value.
{
iter2.SeekToArg( i->first.second );
// the first arg in the pair was not on the command line,
// so just make sure the second isn't there...
if( !iter2.Done() )
{
// arg2 appeared without arg1, so dependency error.
TSTRING arg1, arg2, alias1, alias2;
cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 );
cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 );
// determine in which form the user passed the arguments,
// and construct the error message in the same form
if ( iter1.ActualParam().length() == 2 )
throw eCmdLineDependency( _T("The switch -") + arg1 + _T(" requires -") + arg2 +_T(".") );
else
throw eCmdLineDependency( _T("The switch --") + alias1 + _T(" requires --") + alias2 + _T(".") );
}
}
else if( i->second )
// only make this second check if the dependencies are MUTUAL,
// as indicated (or not) by the bool value.
{
iter2.SeekToArg( i->first.second );
// the first arg in the pair was not on the command line,
// so just make sure the second isn't there...
if( !iter2.Done() )
{
// arg2 appeared without arg1, so dependency error.
TSTRING arg1, arg2, alias1, alias2;
cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 );
cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 );
// determine in which form the user passed the arguments,
// and construct the error message in the same form
if ( iter1.ActualParam().length() == 2 )
throw eCmdLineDependency( _T("The switch -") + arg2 + _T(" requires -") + arg1 +_T(".") );
else
throw eCmdLineDependency( _T("The switch --") + alias2 + _T(" requires --") + alias1 + _T(".") );
}
}
// determine in which form the user passed the arguments,
// and construct the error message in the same form
if ( iter1.ActualParam().length() == 2 )
throw eCmdLineDependency( _T("The switch -") + arg2 + _T(" requires -") + arg1 +_T(".") );
else
throw eCmdLineDependency( _T("The switch --") + alias2 + _T(" requires --") + alias1 + _T(".") );
}
}
} //end for
} //end for
}
@ -355,10 +355,10 @@ void cCmdLineParser::TestDependency()
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::AddMutEx(int argId1, int argId2)
{
// note that I do no checking for duplicates here...
std::pair<int, int> mutEx(argId1, argId2);
ASSERT(argId1 != argId2);
mMutExList.push_back(mutEx);
// note that I do no checking for duplicates here...
std::pair<int, int> mutEx(argId1, argId2);
ASSERT(argId1 != argId2);
mMutExList.push_back(mutEx);
}
///////////////////////////////////////////////////////////////////////////////
@ -366,13 +366,13 @@ void cCmdLineParser::AddMutEx(int argId1, int argId2)
///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual )
{
// again, no checking for duplicates... would a set
// prove to be a better container for this operation?
std::pair< int, int > Args( argId1, argId2 );
std::pair< std::pair< int, int >, bool > Dep( Args, mutual );
// again, no checking for duplicates... would a set
// prove to be a better container for this operation?
std::pair< int, int > Args( argId1, argId2 );
std::pair< std::pair< int, int >, bool > Dep( Args, mutual );
ASSERT(argId1 != argId2);
mDependencyList.push_back( Dep);
ASSERT(argId1 != argId2);
mDependencyList.push_back( Dep);
}
///////////////////////////////////////////////////////////////////////////////
@ -381,29 +381,29 @@ void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual )
#ifdef _DEBUG
void cCmdLineParser::TraceContents(int dl)
{
cDebug d("cCmdLineParser::TraceContents");
if(dl == -1)
dl = cDebug::D_DEBUG;
cDebug d("cCmdLineParser::TraceContents");
if(dl == -1)
dl = cDebug::D_DEBUG;
std::list<cArgData>::const_iterator i;
for(i = mArgData.begin(); i != mArgData.end(); i++)
{
d.Trace(dl, "* Item id:%d\n", i->mId);
for(std::vector<TSTRING>::const_iterator vi = i->mParams.begin(); vi != i->mParams.end(); vi++)
{
d.Trace(dl, "\t%s\n", vi->c_str());
}
}
std::list<cArgData>::const_iterator i;
for(i = mArgData.begin(); i != mArgData.end(); i++)
{
d.Trace(dl, "* Item id:%d\n", i->mId);
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, "--- Switch id table ---\n");
d.Trace(dl, "--- Switch id table ---\n");
cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
for(iter.SeekBegin(); ! iter.Done(); iter.Next())
{
d.Trace(dl, "[%d] %s\n", iter.Val().mId, iter.Key().c_str());
}
cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
for(iter.SeekBegin(); ! iter.Done(); iter.Next())
{
d.Trace(dl, "[%d] %s\n", iter.Val().mId, iter.Key().c_str());
}
d.Trace(dl, "[%d] Final Param List\n", mLastArgInfo.mId);
d.Trace(dl, "[%d] Final Param List\n", mLastArgInfo.mId);
}
#endif
@ -412,28 +412,28 @@ void cCmdLineParser::TraceContents(int dl)
///////////////////////////////////////////////////////////////////////////////
bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const
{
arg = _T("");
alias = _T("");
arg = _T("");
alias = _T("");
cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
for(iter.SeekBegin(); ! iter.Done(); iter.Next())
{
if(iter.Val().mId == argId)
{
TSTRING str = iter.Key();
if((str.length() > 0) && (str[0] == _T('-')))
{
// this is the alias!
alias = (str.c_str() + 1);
}
else
{
// this is the arg...
arg = str;
}
}
}
return ((! arg.empty()) || (! alias.empty()));
cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
for(iter.SeekBegin(); ! iter.Done(); iter.Next())
{
if(iter.Val().mId == argId)
{
TSTRING str = iter.Key();
if((str.length() > 0) && (str[0] == _T('-')))
{
// this is the alias!
alias = (str.c_str() + 1);
}
else
{
// this is the arg...
arg = str;
}
}
}
return ((! arg.empty()) || (! alias.empty()));
}
///////////////////////////////////////////////////////////////////////////////
@ -441,13 +441,13 @@ bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) cons
///////////////////////////////////////////////////////////////////////////////
bool cCmdLineParser::ArgInList(int argId)
{
std::list<cArgData>::iterator i;
for( i = mArgData.begin(); i != mArgData.end(); i++ )
{
if( i->mId == argId )
return true;
}
return false;
std::list<cArgData>::iterator i;
for( i = mArgData.begin(); i != mArgData.end(); i++ )
{
if( i->mId == argId )
return true;
}
return false;
}
@ -458,15 +458,15 @@ bool cCmdLineParser::ArgInList(int argId)
///////////////////////////////////////////////////////////////////////////////
// SeekToArg
///////////////////////////////////////////////////////////////////////////////
bool cCmdLineIter::SeekToArg(int argId) const
bool cCmdLineIter::SeekToArg(int argId) const
{
for(SeekBegin(); ! Done(); Next())
{
if(ArgId() == argId)
return true;
}
for(SeekBegin(); ! Done(); Next())
{
if(ArgId() == argId)
return true;
}
return false;
return false;
}

View File

@ -49,39 +49,39 @@
//=============================================================================
// eCmdLine
//=============================================================================
TSS_EXCEPTION( eCmdLine, eError )
TSS_EXCEPTION( eCmdLineInvalidArg, eCmdLine ) // an arg on the command line is not recognized
TSS_EXCEPTION( eCmdLine, eError )
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( eCmdLineBadParam, eCmdLine ) // wrong number of paramters to the executable (not associated with any arguments)
TSS_EXCEPTION( eCmdLineBadParam, eCmdLine ) // wrong number of paramters to the executable (not associated with any arguments)
TSS_EXCEPTION( eCmdLineBadSwitchPos,eCmdLine ) // a '-' arg appeared after the final parameter list
TSS_EXCEPTION( eCmdLineMutEx, eCmdLine ) // a mutual exclusion error has occured
TSS_EXCEPTION( eCmdLineDependency, eCmdLine ) // a dependency error has occurred.
TSS_EXCEPTION( eCmdLineMultiArg, eCmdLine ) // an arg was found twice in the command line
TSS_EXCEPTION( eCmdLineMutEx, eCmdLine ) // a mutual exclusion error has occured
TSS_EXCEPTION( eCmdLineDependency, eCmdLine ) // a dependency error has occurred.
TSS_EXCEPTION( eCmdLineMultiArg, eCmdLine ) // an arg was found twice in the command line
/*
// cCmdLineParser owns errors 600-699
// these can be turned into a string by using cErrorTable
enum ErrorType
{
ERR_NONE = 601, // no error
ERR_INVALID_ARG = 602, // an arg on the command line is not recognized
ERR_BAD_ARG_PARAMS = 603, // wrong number of parameters to an argument
ERR_BAD_PARAMS = 604, // wrong number of paramters to the executable (not associated with any arguments)
ERR_SWITCH_AFTER_FINAL_LIST = 605, // a '-' arg appeared after the final paramter list
ERR_MUTUAL_EXCLUSION = 606, // a mutual exclusion error has occured
ERR_MULTIPLE_ARG = 607, // an arg was found twice in the command line
// cCmdLineParser owns errors 600-699
// these can be turned into a string by using cErrorTable
enum ErrorType
{
ERR_NONE = 601, // no error
ERR_INVALID_ARG = 602, // an arg on the command line is not recognized
ERR_BAD_ARG_PARAMS = 603, // wrong number of parameters to an argument
ERR_BAD_PARAMS = 604, // wrong number of paramters to the executable (not associated with any arguments)
ERR_SWITCH_AFTER_FINAL_LIST = 605, // a '-' arg appeared after the final paramter list
ERR_MUTUAL_EXCLUSION = 606, // a mutual exclusion error has occured
ERR_MULTIPLE_ARG = 607, // an arg was found twice in the command line
ERR_INVALID // top of enum
};
ERR_INVALID // top of enum
};
// for storing error information
ErrorType mCurError;
TSTRING mCurErrorString;
void GetErrorInfo(ErrorType& et, TSTRING& errorData) const;
// returns information on the type of error that occured in a Parse() command. Only
// returns valid information if Parse() had just been called and returned false. A
// second call to Parse() might alter existing error info
// for storing error information
ErrorType mCurError;
TSTRING mCurErrorString;
void GetErrorInfo(ErrorType& et, TSTRING& errorData) const;
// returns information on the type of error that occured in a Parse() command. Only
// returns valid information if Parse() had just been called and returned false. A
// second call to Parse() might alter existing error info
*/
//=============================================================================
@ -90,176 +90,176 @@ TSS_EXCEPTION( eCmdLineMultiArg, eCmdLine ) // an arg was found twice in the com
class cCmdLineParser
{
public:
cCmdLineParser();
~cCmdLineParser();
cCmdLineParser();
~cCmdLineParser();
enum ParamCount
{
PARAM_NONE, // no parameters to arg
PARAM_ONE, // one parameter to arg
PARAM_MANY, // zero or more paramters to arg
enum ParamCount
{
PARAM_NONE, // no parameters to arg
PARAM_ONE, // one parameter 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);
// this method should be called for each argument that can appear on the
// command line.
// argId -- a number that uniquely identifies the argument; no two arguments
// may have the same id (ASSERT-enforced)
// arg -- string that comes after the '-'. can be _T("") if there is only
// a string representation
// alias -- string that comes after '--' which has the same meaning. Can be _T("")
// if there is no alias. If both arg and alias are empty strings, then this arg
// represents the list of arguments that comes at the end of the command line
// numParams -- number of parameters that this argument needs
void AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed = false);
// this method should be called for each argument that can appear on the
// command line.
// argId -- a number that uniquely identifies the argument; no two arguments
// may have the same id (ASSERT-enforced)
// arg -- string that comes after the '-'. can be _T("") if there is only
// a string representation
// alias -- string that comes after '--' which has the same meaning. Can be _T("")
// if there is no alias. If both arg and alias are empty strings, then this arg
// 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);
// 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
// value ERR_MUTUAL_EXCLUSION will be set.
void AddMutEx(int argId1, int argId2);
// 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
// value ERR_MUTUAL_EXCLUSION will be set.
void AddDependency(int argId1, int argId2, bool mutual = false );
// This adds a dependency constraint. When Parse() is called, if argId1
// 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
// 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.
void AddDependency(int argId1, int argId2, bool mutual = false );
// This adds a dependency constraint. When Parse() is called, if argId1
// 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
// 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.
void Parse(int argc, const TCHAR *const * argv); // throw eCmdLine
// 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
// the input was invalid in some way; the actual error can be determined by calling
// GetErrorInfo() below.
void Parse(int argc, const TCHAR *const * argv); // throw eCmdLine
// 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
// the input was invalid in some way; the actual error can be determined by calling
// GetErrorInfo() below.
void Clear();
// clear out all information that this class contains
void Clear();
// clear out all information that this class contains
bool LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const;
// 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.
bool LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const;
// 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.
#ifdef _DEBUG
void TraceContents(int dl = -1) ;
void TraceContents(int dl = -1) ;
#endif
private:
void TestMutEx();
// tests for mutual exclusion violations; if it fails, the current error is set and false
// is returned.
void TestDependency();
// tests for all dependency violations.
bool ArgInList(int argId);
// 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
void TestMutEx();
// tests for mutual exclusion violations; if it fails, the current error is set and false
// is returned.
void TestDependency();
// tests for all dependency violations.
bool ArgInList(int argId);
// 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
// for storing information on paramers
struct cArgInfo
{
int mId;
ParamCount mNumParams;
// for storing information on paramers
struct cArgInfo
{
int mId;
ParamCount mNumParams;
cArgInfo(int i = -1, ParamCount p = PARAM_INVALID) : mId(i), mNumParams(p) {}
};
// for storing parsed argv information
struct cArgData
{
int mId;
std::vector<TSTRING> mParams;
TSTRING mActualParam; // a string representation of what was actually on the command line
cArgInfo(int i = -1, ParamCount p = PARAM_INVALID) : mId(i), mNumParams(p) {}
};
// for storing parsed argv information
struct cArgData
{
int mId;
std::vector<TSTRING> mParams;
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;
cArgInfo mLastArgInfo; // info on the argument that comes at the end of the command line (with no associated '-x' or '--x')
std::list<cArgData> mArgData;
std::list<std::pair<int,int> > mMutExList; // all of the mutual exclusions
std::list< std::pair < std::pair<int,int>, bool > > mDependencyList; // all of the dependencies
std::set< int > mMultipleAllowed;
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')
std::list<cArgData> mArgData;
std::list<std::pair<int,int> > mMutExList; // all of the mutual exclusions
std::list< std::pair < std::pair<int,int>, bool > > mDependencyList; // all of the dependencies
std::set< int > mMultipleAllowed;
friend class cCmdLineIter;
friend class cCmdLineIter;
};
///////////////////////////////////////////////////////////////////////////////
// cCmdLineIter -- used to iterate over the tokenized command line parameters;
// is only useful after cCmdLineParser::Parse() has been called.
// is only useful after cCmdLineParser::Parse() has been called.
///////////////////////////////////////////////////////////////////////////////
class cCmdLineIter
{
public:
cCmdLineIter(const cCmdLineParser& parser);
cCmdLineIter(const cCmdLineParser& parser);
// iteration
void SeekBegin() const;
bool Done() const;
bool IsEmpty() const;
void Next() const;
// iteration
void SeekBegin() const;
bool Done() const;
bool IsEmpty() const;
void Next() const;
bool SeekToArg(int argId) const;
// seeks to the argument with the given argId. returns
// false and Done() == true if it couldn't find it.
bool SeekToArg(int argId) const;
// seeks to the argument with the given argId. returns
// false and Done() == true if it couldn't find it.
// access to the argument data
int ArgId() const;
// returns the id of this arg; ASSERTs if Done() == true
int NumParams() const;
// returns the number of parameters this argument has
const TSTRING& ActualParam() const;
// returns exactly what was passed on the command line (ie -- what the user typed)
const TSTRING& ParamAt(int index) const;
// returns the parameter at the specified index. ASSERTs if
// the index is out of range.
// access to the argument data
int ArgId() const;
// returns the id of this arg; ASSERTs if Done() == true
int NumParams() const;
// returns the number of parameters this argument has
const TSTRING& ActualParam() const;
// returns exactly what was passed on the command line (ie -- what the user typed)
const TSTRING& ParamAt(int index) const;
// returns the parameter at the specified index. ASSERTs if
// the index is out of range.
private:
const std::list<cCmdLineParser::cArgData>& mList;
mutable std::list<cCmdLineParser::cArgData>::const_iterator mIter;
const std::list<cCmdLineParser::cArgData>& mList;
mutable std::list<cCmdLineParser::cArgData>::const_iterator mIter;
};
//#############################################################################
// inline implementation
//#############################################################################
inline cCmdLineIter::cCmdLineIter(const cCmdLineParser& parser) :
mList(parser.mArgData)
mList(parser.mArgData)
{
SeekBegin();
SeekBegin();
}
inline void cCmdLineIter::SeekBegin() const
inline void cCmdLineIter::SeekBegin() const
{
mIter = mList.begin();
mIter = mList.begin();
}
inline bool cCmdLineIter::Done() const
inline bool cCmdLineIter::Done() const
{
return (mIter == mList.end());
return (mIter == mList.end());
}
inline bool cCmdLineIter::IsEmpty() const
inline bool cCmdLineIter::IsEmpty() const
{
return (mList.size() == 0);
return (mList.size() == 0);
}
inline void cCmdLineIter::Next() const
inline void cCmdLineIter::Next() const
{
mIter++;
mIter++;
}
inline int cCmdLineIter::ArgId() const
{
ASSERT(! Done());
return mIter->mId;
ASSERT(! Done());
return mIter->mId;
}
inline int cCmdLineIter::NumParams() const
{
ASSERT(! Done());
return mIter->mParams.size();
ASSERT(! Done());
return mIter->mParams.size();
}
inline const TSTRING& cCmdLineIter::ActualParam() const
inline const TSTRING& cCmdLineIter::ActualParam() const
{
ASSERT(! Done());
return mIter->mActualParam;
ASSERT(! Done());
return mIter->mActualParam;
}
inline const TSTRING& cCmdLineIter::ParamAt(int index) const
inline const TSTRING& cCmdLineIter::ParamAt(int index) const
{
ASSERT((index >= 0) && (index < NumParams()));
return mIter->mParams[index];
ASSERT((index >= 0) && (index < NumParams()));
return mIter->mParams[index];
}

View File

@ -1,178 +0,0 @@
//
// The developer of the original code and/or files is Tripwire, Inc.
// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire,
// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights
// reserved.
//
// This program is free software. The contents of this file are subject
// to the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. You may redistribute it and/or modify it
// only in compliance with the GNU General Public License.
//
// This program is distributed in the hope that it will be useful.
// However, this program is distributed AS-IS WITHOUT ANY
// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// Nothing in the GNU General Public License or any other license to use
// the code or files shall permit you to use Tripwire's trademarks,
// service marks, or other intellectual property without Tripwire's
// prior written consent.
//
// If you have any questions, please contact Tripwire, Inc. at either
// info@tripwire.org or www.tripwire.org.
//
///////////////////////////////////////////////////////////////////////////////
// cmdlineparser_t.cpp
#include "stdcore.h"
#include "cmdlineparser.h"
#include "test/test.h"
//#include "tw/twutil.h"
//#include "tw/twstrings.h"
const int argc1 = 9;
const TCHAR* argv1[] =
{
_T("tripwire.exe"),
_T("-m"),
_T("Init"),
_T("-tp"),
_T("one"),
_T("two"),
_T("--verbose"),
_T("frog"),
_T("cat")
};
const int argc2 = 3;
const TCHAR* argv2[] =
{
_T("tripwire.exe"),
_T("-m"),
_T("-v")
};
const int argc3 = 3;
const TCHAR* argv3[] =
{
_T("tripwire.exe"),
_T("dog"),
_T("-v"),
};
// test with the last param wanting 1 or 0 parameters :-)
const int argc4 = 5;
const TCHAR* argv4[] =
{
_T("tripwire.exe"),
_T("-tp"),
_T("-v"),
_T("frog"),
_T("cat")
};
const int argc5 = 4;
const TCHAR* argv5[] =
{
_T("tripwire.exe"),
_T("-tp"),
_T("-v"),
_T("frog")
};
static void PrintCmdLine(int argc, const TCHAR** argv, cDebug d)
{
TSTRING str;
d.TraceDebug("Testing command line:\n");
for(int i=0; i < argc; i++)
{
str += argv[i];
str += _T(" ");
}
d.TraceDebug(_T(">>>%s\n"), str.c_str());
}
void TestCmdLineParser()
{
enum ArgId { ID_M, ID_TP, ID_V, ID_UNNAMED };
try {
cCmdLineParser p;
p.AddArg(ID_M, TSTRING(_T("m")), TSTRING(_T("mode")), cCmdLineParser::PARAM_ONE);
p.AddArg(ID_TP, TSTRING(_T("tp")), TSTRING(_T("twoparam")), cCmdLineParser::PARAM_MANY);
p.AddArg(ID_V, TSTRING(_T("v")), TSTRING(_T("verbose")), cCmdLineParser::PARAM_NONE);
p.AddArg(ID_UNNAMED, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_MANY);
cDebug d("TestCmdLineParser");
PrintCmdLine(argc1, argv1, d);
p.Parse(argc1, argv1);
#ifdef _DEBUG
p.TraceContents();
#endif
PrintCmdLine(argc2, argv2, d);
p.Parse(argc2, argv2); // should fail.
#ifdef _DEBUG
p.TraceContents();
#endif
PrintCmdLine(argc3, argv3, d);
p.Parse(argc3, argv3); // should fail
#ifdef _DEBUG
p.TraceContents();
#endif
PrintCmdLine(argc4, argv4, d);
p.Parse(argc4, argv4);
#ifdef _DEBUG
p.TraceContents();
#endif
/*
// TODO - test mutual exclusion...
cCmdLineParser::ErrorType et;
TSTRING errStr;
d.TraceDebug("** Making -m and -v mutually exclusive, then running on first cmd line...\n");
p.AddMutEx(ID_M, ID_V);
p.Parse(argc1, argv1); // should fail
p.GetErrorInfo(et, errStr);
TEST(et == cCmdLineParser::ERR_MUTUAL_EXCLUSION);
d.TraceDebug(_T("Mutual exclusion test worked; here is the error string: %s\n"), errStr.c_str());
*/
// make the command line want one parameter
d.TraceDebug("** Changing cmd line to only want one last param...\n");
p.AddArg(ID_UNNAMED, TSTRING(_T("")), TSTRING(_T("")), cCmdLineParser::PARAM_ONE);
PrintCmdLine(argc4, argv4, d);
p.Parse(argc4, argv4); // should fail
#ifdef _DEBUG
p.TraceContents();
#endif
PrintCmdLine(argc5, argv5, d);
p.Parse(argc5, argv5);
#ifdef _DEBUG
p.TraceContents();
#endif
// TODO -- test a bunch more!!!
}
catch (eCmdLine &e)
{
TCERR << _T("Command line error: ");
TCERR << e.GetMsg() << std::endl;
TEST(false);
}
}

View File

@ -84,9 +84,9 @@ TSS_EXCEPTION( eConverterUnknownCodepage, eConverter );
* or a byte value is not a character, it is cast to a reserved
* region of UCS2 ( 0xE000 - 0xE0FF ).
* CONSTRAINTS:
*
*
* INVARIANTS:
*
*
*/
class iCodeConverter
{

View File

@ -46,7 +46,7 @@ TSS_ImplementPackage( cCore )
cCore::cCore()
{
TSS_REGISTER_PKG_ERRORS( core );
TSS_REGISTER_PKG_ERRORS( core );
// NOTE: Initialize code converter when cCore is a dependency
// of another package (created on first call to GetInstance(),

View File

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

View File

@ -68,34 +68,34 @@ TSS_REGISTER_ERROR( eBadCmdLine(), _T("Command line error.") );
/// Archive
TSS_REGISTER_ERROR( eArchive(), _T("Archive error.") )
TSS_REGISTER_ERROR( eArchiveOpen(), _T("File could not be opened.") )
TSS_REGISTER_ERROR( eArchiveWrite(), _T("File could not be written.") )
TSS_REGISTER_ERROR( eArchiveRead(), _T("File could not be read.") )
TSS_REGISTER_ERROR( eArchiveEOF(), _T("End of file reached.") )
TSS_REGISTER_ERROR( eArchiveSeek(), _T("File seek failed.") )
TSS_REGISTER_ERROR( eArchiveMemmap(), _T("Memory mapped archive file invalid.") )
TSS_REGISTER_ERROR( eArchive(), _T("Archive error.") )
TSS_REGISTER_ERROR( eArchiveOpen(), _T("File could not be opened.") )
TSS_REGISTER_ERROR( eArchiveWrite(), _T("File could not be written.") )
TSS_REGISTER_ERROR( eArchiveRead(), _T("File could not be read.") )
TSS_REGISTER_ERROR( eArchiveEOF(), _T("End of file reached.") )
TSS_REGISTER_ERROR( eArchiveSeek(), _T("File seek failed.") )
TSS_REGISTER_ERROR( eArchiveMemmap(), _T("Memory mapped archive file invalid.") )
TSS_REGISTER_ERROR( eArchiveOutOfMem(), _T("Archive ran out of memory.") )
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( 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.") )
/// File
TSS_REGISTER_ERROR( eFile(), _T("File error.") )
TSS_REGISTER_ERROR( eFileOpen(), _T("File could not be opened.") )
TSS_REGISTER_ERROR( eFileWrite(), _T("File could not be written.") )
TSS_REGISTER_ERROR( eFileRead(), _T("File could not be read.") )
TSS_REGISTER_ERROR( eFileEOF(), _T("End of file reached.") )
TSS_REGISTER_ERROR( eFileSeek(), _T("File seek failed.") )
TSS_REGISTER_ERROR( eFileInvalidOp(), _T("File logic error.") )
TSS_REGISTER_ERROR( eFileTrunc(), _T("File could not be truncated.") )
TSS_REGISTER_ERROR( eFileClose(), _T("File could not be closed.") )
TSS_REGISTER_ERROR( eFileFlush(), _T("File could not be flushed.") )
TSS_REGISTER_ERROR( eFileRewind(), _T("File could not be rewound.") )
TSS_REGISTER_ERROR( eFile(), _T("File error.") )
TSS_REGISTER_ERROR( eFileOpen(), _T("File could not be opened.") )
TSS_REGISTER_ERROR( eFileWrite(), _T("File could not be written.") )
TSS_REGISTER_ERROR( eFileRead(), _T("File could not be read.") )
TSS_REGISTER_ERROR( eFileEOF(), _T("End of file reached.") )
TSS_REGISTER_ERROR( eFileSeek(), _T("File seek failed.") )
TSS_REGISTER_ERROR( eFileInvalidOp(), _T("File logic error.") )
TSS_REGISTER_ERROR( eFileTrunc(), _T("File could not be truncated.") )
TSS_REGISTER_ERROR( eFileClose(), _T("File could not be closed.") )
TSS_REGISTER_ERROR( eFileFlush(), _T("File could not be flushed.") )
TSS_REGISTER_ERROR( eFileRewind(), _T("File could not be rewound.") )
/// Win32
@ -106,32 +106,32 @@ TSS_REGISTER_ERROR(eUnix(), _T("Unix API failure.") )
/// 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.") )
/// Serializer
TSS_REGISTER_ERROR( eSerializerUnknownType(), _T("Unknown type encountered in file.\nFile format may not be valid for this platform.") )
TSS_REGISTER_ERROR( eSerializerInputStreamFmt(), _T("Invalid input stream format.") )
TSS_REGISTER_ERROR( eSerializerOutputStreamFmt(), _T("Invalid output stream format.") )
TSS_REGISTER_ERROR( eSerializerInputStremTypeArray(), _T("A bad index was encountered in file.") )
TSS_REGISTER_ERROR( eSerializerArchive(), _T("File read encountered an archive error.") )
TSS_REGISTER_ERROR( eSerializerVersionMismatch(), _T("File version mismatch.") )
TSS_REGISTER_ERROR( eSerializerEncryption(), _T("File encryption error.") )
TSS_REGISTER_ERROR( eSerializer(), _T("File format error.") )
TSS_REGISTER_ERROR( eSerializerUnknownType(), _T("Unknown type encountered in file.\nFile format may not be valid for this platform.") )
TSS_REGISTER_ERROR( eSerializerInputStreamFmt(), _T("Invalid input stream format.") )
TSS_REGISTER_ERROR( eSerializerOutputStreamFmt(), _T("Invalid output stream format.") )
TSS_REGISTER_ERROR( eSerializerInputStremTypeArray(), _T("A bad index was encountered in file.") )
TSS_REGISTER_ERROR( eSerializerArchive(), _T("File read encountered an archive error.") )
TSS_REGISTER_ERROR( eSerializerVersionMismatch(), _T("File version mismatch.") )
TSS_REGISTER_ERROR( eSerializerEncryption(), _T("File encryption error.") )
TSS_REGISTER_ERROR( eSerializer(), _T("File format error.") )
/// Command Line
TSS_REGISTER_ERROR( eCmdLine(), _T("Command line parsing error.") )
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( eCmdLineBadParam(), _T("Incorrect number of parameters on command line.") )
TSS_REGISTER_ERROR( eCmdLine(), _T("Command line parsing error.") )
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( eCmdLineBadParam(), _T("Incorrect number of parameters on command line.") )
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( eCmdLineDependency(), _T("Command line parameter missing.") )
TSS_REGISTER_ERROR( eCmdLineMultiArg(), _T("Command line argument specified more than once.") )
TSS_REGISTER_ERROR( eCmdLineMutEx(), _T("Specified command line switches are mutually exclusive.") )
TSS_REGISTER_ERROR( eCmdLineDependency(), _T("Command line parameter missing.") )
TSS_REGISTER_ERROR( eCmdLineMultiArg(), _T("Command line argument specified more than once.") )
/// TWLocale

View File

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

View File

@ -51,11 +51,11 @@ TSS_BeginStringtable( cCore )
TSS_StringEntry( core::STR_ERROR_CONTINUING, _T("Continuing...") ),
TSS_StringEntry( core::STR_ERR2_FILENAME, _T("Filename: ") ),
TSS_StringEntry( core::STR_ERROR_FILENAME, _T("Filename: ") ),
TSS_StringEntry( core::STR_UNKNOWN, _T("Unknown") ),
TSS_StringEntry( core::STR_NUMBER_TOO_BIG, _T("Number too big") ),
TSS_StringEntry( core::STR_SIGNAL, _T("Software interrupt forced exit:") ),
TSS_StringEntry( core::STR_NEWLINE, _T("\n") ),
TSS_StringEntry( core::STR_MEMARCHIVE_FILENAME, _T("Error occured in internal memory file") ),
TSS_StringEntry( core::STR_UNKNOWN, _T("Unknown") ),
TSS_StringEntry( core::STR_NUMBER_TOO_BIG, _T("Number too big") ),
TSS_StringEntry( core::STR_SIGNAL, _T("Software interrupt forced exit:") ),
TSS_StringEntry( core::STR_NEWLINE, _T("\n") ),
TSS_StringEntry( core::STR_MEMARCHIVE_FILENAME, _T("Error occured in internal memory file") ),
TSS_StringEntry( core::STR_MEMARCHIVE_ERRSTR, _T("") ),
TSS_StringEntry( core::STR_ENDOFTIME, _T("Tripwire is not designed to run past the year 2038.\nNow exiting...") ),
TSS_StringEntry( core::STR_UNKNOWN_TIME, _T("Unknown time") ),

View File

@ -59,7 +59,7 @@ TSS_BeginStringIds( core )
STR_ERROR_FILENAME,
STR_NUMBER_TOO_BIG,
STR_UNKNOWN,
STR_SIGNAL,
STR_SIGNAL,
STR_NEWLINE,
STR_MEMARCHIVE_FILENAME,
STR_MEMARCHIVE_ERRSTR,

View File

@ -33,7 +33,7 @@
*
*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* James W. Williams of NASA Goddard Space Flight Center.
@ -48,8 +48,8 @@
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
@ -85,58 +85,58 @@
#define BUFSIZE 4096
static uint32 crctab[] = {
0x0,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,
0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,
0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,
0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,
0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,
0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,
0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,
0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,
0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,
0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,
0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,
0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,
0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,
0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,
0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,
0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,
0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,
0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,
0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,
0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,
0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,
0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,
0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,
0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,
0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,
0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,
0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,
0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,
0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,
0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,
0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,
0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,
0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,
0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
0x0,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,
0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,
0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,
0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,
0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,
0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,
0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,
0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,
0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,
0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,
0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,
0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,
0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,
0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,
0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,
0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,
0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,
0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,
0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,
0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,
0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,
0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,
0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,
0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,
0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,
0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,
0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,
0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,
0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,
0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,
0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,
0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,
0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,
0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
/*
@ -145,8 +145,8 @@ static uint32 crctab[] = {
* locations to store the crc and the number of bytes read. It returns 0 on
* success and 1 on failure. Errno is set on failure.
*/
#define COMPUTE(var, ch) (var) = ((var) << 8) ^ \
crctab[0xff & (unsigned)((var) >> 24 ^ (ch))]
#define COMPUTE(var, ch) (var) = ((var) << 8) ^ \
crctab[0xff & (unsigned)((var) >> 24 ^ (ch))]
void crcInit( CRC_INFO& crcInfo )
{
@ -156,22 +156,22 @@ void crcInit( CRC_INFO& crcInfo )
void crcUpdate( CRC_INFO& crcInfo, const uint8* pbData, int cbDataLen )
{
for( int i = 0; i < cbDataLen; i++, pbData++ )
{
COMPUTE( crcInfo.crc, *pbData );
}
for( int i = 0; i < cbDataLen; i++, pbData++ )
{
COMPUTE( crcInfo.crc, *pbData );
}
crcInfo.cbTotalLen += cbDataLen;
}
void crcFinit( CRC_INFO& crcInfo )
{
// include the length
//
// include the length
//
uint32 len = crcInfo.cbTotalLen;
for(; len != 0; len >>= 8)
COMPUTE( crcInfo.crc, len & 0xff );
for(; len != 0; len >>= 8)
COMPUTE( crcInfo.crc, len & 0xff );
crcInfo.crc = ~(crcInfo.crc) & 0xFFFFFFFF;
crcInfo.crc = ~(crcInfo.crc) & 0xFFFFFFFF;
}

View File

@ -48,7 +48,7 @@ void crcUpdate( CRC_INFO& crcInfo, const uint8* pbData, int cbDataLen );
void crcFinit ( CRC_INFO& crcInfo );
// calculates the crc for len bytes starting at pBuf
// calculates the crc for len bytes starting at pBuf
//Wrapper function for CRC32 in crc32.cpp
#endif //__CRC32_H

View File

@ -44,10 +44,10 @@
#include <fstream>
#include <cstdio>
int cDebug::mDebugLevel(10);
uint32 cDebug::mOutMask(cDebug::OUT_TRACE);
int cDebug::mDebugLevel(10);
uint32 cDebug::mOutMask(cDebug::OUT_TRACE);
std::ofstream cDebug::logfile;
//mDebugLevel default == 10, mOutMask default == OUT_TRACE.
//mDebugLevel default == 10, mOutMask default == OUT_TRACE.
///////////////////////////////////////////////////////////////////////////////
// Constructors and Destructor
@ -63,13 +63,13 @@ cDebug::cDebug(const char* label)
cDebug::cDebug(const cDebug &rhs)
{
strcpy(mLabel, rhs.mLabel);
strcpy(mLabel, rhs.mLabel);
}
cDebug::~cDebug()
{
if(logfile)
logfile.close();
if(logfile)
logfile.close();
}
///////////////////////////////////////////////////////////////////////////////
@ -79,38 +79,38 @@ cDebug::~cDebug()
///////////////////////////////////////////////////////////////////////////////
void cDebug::Trace(int levelNum, const char* format, ...)
{
if (levelNum > mDebugLevel)
return;
if (levelNum > mDebugLevel)
return;
// create the output buffer
va_list args;
va_start(args, format);
DoTrace(format, args);
DoTrace(format, args);
va_end(args);
}
void cDebug::Trace(int levelNum, const wchar_t* format, ...)
{
if (levelNum > mDebugLevel)
return;
if (levelNum > mDebugLevel)
return;
// create the output buffer
va_list args;
va_start(args, format);
DoTrace(format, args);
DoTrace(format, args);
va_end(args);
}
///////////////////////////////////////////////////////////////////////////////
// DoTrace()
// internal helper function -- does the actual printing to logfile,
// console, etc...
// internal helper function -- does the actual printing to logfile,
// console, etc...
///////////////////////////////////////////////////////////////////////////////
void cDebug::DoTrace(const char *format, va_list &args)
{
size_t guard1 = 0xBABABABA;
char out[2048];
char out[2048];
size_t guard2 = 0xBABABABA;
vsprintf(out, format, args);
@ -118,32 +118,32 @@ void cDebug::DoTrace(const char *format, va_list &args)
ASSERT(guard1 == 0xBABABABA && guard2 == 0xBABABABA); // string was too long
ASSERT(strlen(out) < 1024);
std::ostringstream ostr;
ostr.setf(std::ios::left);
ostr.width(40);
ostr << mLabel;
ostr.width(0);
ostr << out;
std::ostringstream ostr;
ostr.setf(std::ios::left);
ostr.width(40);
ostr << mLabel;
ostr.width(0);
ostr << out;
if ((mOutMask & OUT_STDOUT) != 0)
{
std::cout << ostr.str().c_str();
std::cout.flush();
std::cout.flush();
}
//
//make it output to log file!
//
if ((mOutMask & OUT_FILE) != 0)
//make it output to log file!
//
if ((mOutMask & OUT_FILE) != 0)
{
// the logfile is narrow chars only...
logfile.setf(std::ios::left);
logfile.width(40);
logfile << mLabel;
logfile.width(0);
logfile << out;
logfile.flush();
// the logfile is narrow chars only...
logfile.setf(std::ios::left);
logfile.width(40);
logfile << mLabel;
logfile.width(0);
logfile << out;
logfile.flush();
}
}
@ -156,42 +156,42 @@ void cDebug::DoTrace(const wchar_t *format, va_list &args)
#else
size_t guard1 = 0xBABABABA;
wchar_t out[2048];
wchar_t out[2048];
size_t guard2 = 0xBABABABA;
vswprintf(out, format, args);
ASSERT(guard1 == 0xBABABABA && guard2 == 0xBABABABA); // string was too long
char nout[1024];
if (wcstombs(nout, out, 1024) == -1)
if (wcstombs(nout, out, 1024) == -1)
strcpy(nout, "XXX Unconvertable wide char detected in cDebug::DoTrace()\n");
std::ostringstream ostr;
ostr.setf(std::ios::left);
ostr.width(40);
ostr << mLabel;
ostr.width(0);
ostr << nout;
ostr.setf(std::ios::left);
ostr.width(40);
ostr << mLabel;
ostr.width(0);
ostr << nout;
if ((mOutMask & OUT_STDOUT) != 0)
{
std::cout << ostr.str().c_str();
std::cout.flush();
std::cout << ostr.str().c_str();
std::cout.flush();
}
//
//make it output to log file!
//
if ((mOutMask & OUT_FILE) != 0)
//make it output to log file!
//
if ((mOutMask & OUT_FILE) != 0)
{
// the logfile is narrow chars only...
logfile.setf(std::ios::left);
logfile.width(40);
logfile << mLabel;
logfile.width(0);
logfile << out;
logfile.flush();
// the logfile is narrow chars only...
logfile.setf(std::ios::left);
logfile.width(40);
logfile << mLabel;
logfile.width(0);
logfile << out;
logfile.flush();
}
#endif // IS_UNIX
}
@ -200,151 +200,151 @@ void cDebug::DoTrace(const wchar_t *format, va_list &args)
//
// 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, ...)
{
if (D_ALWAYS > mDebugLevel)
return;
if (D_ALWAYS > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceError(const char *format, ...)
{
if (D_ERROR > mDebugLevel)
return;
if (D_ERROR > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceWarning(const char *format, ...)
{
if (D_WARNING > mDebugLevel)
return;
if (D_WARNING > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceDebug(const char *format, ...)
{
if (D_DEBUG > mDebugLevel)
return;
if (D_DEBUG > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceDetail(const char *format, ...)
{
if (D_DETAIL > mDebugLevel)
return;
if (D_DETAIL > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceNever(const char *format, ...)
{
if (D_NEVER > mDebugLevel)
return;
if (D_NEVER > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceAlways(const wchar_t *format, ...)
{
if (D_ALWAYS > mDebugLevel)
return;
if (D_ALWAYS > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceError(const wchar_t *format, ...)
{
if (D_ERROR > mDebugLevel)
return;
if (D_ERROR > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceWarning(const wchar_t *format, ...)
{
if (D_WARNING > mDebugLevel)
return;
if (D_WARNING > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceDebug(const wchar_t *format, ...)
{
if (D_DEBUG > mDebugLevel)
return;
if (D_DEBUG > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceDetail(const wchar_t *format, ...)
{
if (D_DETAIL > mDebugLevel)
return;
if (D_DETAIL > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceNever(const wchar_t *format, ...)
{
if (D_NEVER > mDebugLevel)
return;
if (D_NEVER > mDebugLevel)
return;
// fill up arglist, and pass to printing routine
// fill up arglist, and pass to printing routine
va_list args;
va_start(args, format);
DoTrace(format, args);
va_end(args);
va_start(args, format);
DoTrace(format, args);
va_end(args);
}
void cDebug::TraceVaArgs( int iDebugLevel, const char *format, va_list &args )
@ -367,15 +367,15 @@ void cDebug::TraceVaArgs( int iDebugLevel, const wchar_t *format, va_list &args
///////////////////////////////////////////////////////////////////////////////
bool cDebug::AddOutTarget(OutTarget target)
{
if (target == OUT_STDOUT)
mOutMask |= OUT_STDOUT;
if (target == OUT_TRACE)
mOutMask |= OUT_TRACE;
if (target == OUT_FILE) {
mOutMask |= OUT_FILE;
return false;
}
return true;
if (target == OUT_STDOUT)
mOutMask |= OUT_STDOUT;
if (target == OUT_TRACE)
mOutMask |= OUT_TRACE;
if (target == OUT_FILE) {
mOutMask |= OUT_FILE;
return false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
@ -383,15 +383,15 @@ bool cDebug::AddOutTarget(OutTarget target)
///////////////////////////////////////////////////////////////////////////////
bool cDebug::RemoveOutTarget(OutTarget target)
{
if (!HasOutTarget(target))
return true;
if (target == OUT_STDOUT)
mOutMask ^= OUT_STDOUT;
if (target == OUT_TRACE)
mOutMask ^= OUT_TRACE;
if (target == OUT_FILE)
mOutMask ^= OUT_FILE;
return true;
if (!HasOutTarget(target))
return true;
if (target == OUT_STDOUT)
mOutMask ^= OUT_STDOUT;
if (target == OUT_TRACE)
mOutMask ^= OUT_TRACE;
if (target == OUT_FILE)
mOutMask ^= OUT_FILE;
return true;
}
///////////////////////////////////////////////////////////////////////////////
@ -399,15 +399,15 @@ bool cDebug::RemoveOutTarget(OutTarget target)
///////////////////////////////////////////////////////////////////////////////
bool cDebug::HasOutTarget(OutTarget target)
{
if (target == OUT_STDOUT)
return ((mOutMask & OUT_STDOUT) != 0);
else if (target == OUT_TRACE)
return ((mOutMask & OUT_TRACE) != 0);
else if (target == OUT_FILE)
return ((mOutMask & OUT_FILE) != 0);
else //ambiguous input, or too many bits set in target
return false;
if (target == OUT_STDOUT)
return ((mOutMask & OUT_STDOUT) != 0);
else if (target == OUT_TRACE)
return ((mOutMask & OUT_TRACE) != 0);
else if (target == OUT_FILE)
return ((mOutMask & OUT_FILE) != 0);
else //ambiguous input, or too many bits set in target
return false;
}
///////////////////////////////////////////////////////////////////////////////
@ -416,22 +416,22 @@ bool cDebug::HasOutTarget(OutTarget target)
///////////////////////////////////////////////////////////////////////////////
bool cDebug::SetOutputFile(const char* filename)
{
// TODO -- make sure this does the right thing if a log file is
// already open!
// TODO -- make this work with wide chars
if (!logfile)
// TODO -- make sure this does the right thing if a log file is
// already open!
// TODO -- make this work with wide chars
if (!logfile)
logfile.open(filename, std::ios_base::out | std::ios_base::ate | std::ios_base::app);
else
logfile.setf(std::ios_base::hex, std::ios_base::basefield);
//make sure info. will not be clobbered.
else
logfile.setf(std::ios_base::hex, std::ios_base::basefield);
//make sure info. will not be clobbered.
//Should be open now- if not, abort.
if (!logfile) {
mOutMask ^= OUT_FILE;
return false;
} else
mOutMask |= OUT_FILE;
return true;
//Should be open now- if not, abort.
if (!logfile) {
mOutMask ^= OUT_FILE;
return false;
} else
mOutMask |= OUT_FILE;
return true;
}
//////////////////////////////////////////////////////////////////////////////
@ -440,7 +440,7 @@ bool cDebug::SetOutputFile(const char* filename)
//////////////////////////////////////////////////////////////////////////////
void cDebug::DebugOut( const char* lpOutputString, ... )
{
char buf[2048];
char buf[2048];
// create the output buffer
va_list args;
va_start(args, lpOutputString);
@ -449,25 +449,25 @@ void cDebug::DebugOut( const char* lpOutputString, ... )
#ifdef _UNICODE
wchar_t wbuf[2048];
if (mbstowcs(wbuf, buf, strlen(buf)+1) == -1)
if (mbstowcs(wbuf, buf, strlen(buf)+1) == -1)
wcscpy(wbuf, _T("XXX Unconvertable mb character detected in cDebug::DebugOut()\n") );
#if !USE_OUTPUT_DEBUG_STRING
#ifdef _DEBUG
TCERR << wbuf;
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(wbuf);
#endif // USE_OUTPUT_DEBUG_STRING
#else // _UNICODE
TCERR << wbuf;
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(wbuf);
#endif // USE_OUTPUT_DEBUG_STRING
#else // _UNICODE
#if !USE_OUTPUT_DEBUG_STRING
#ifdef _DEBUG
TCERR << buf;
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(buf);
#endif // USE_OUTPUT_DEBUG_STRING
#endif // _UNICODE
TCERR << buf;
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(buf);
#endif // USE_OUTPUT_DEBUG_STRING
#endif // _UNICODE
TCOUT.flush();
}
@ -480,7 +480,7 @@ void cDebug::DebugOut( const wchar_t* lpOutputString, ... )
#if IS_UNIX
char mbformatbuf[1024];
char buf[1024];
// if (wcstombs(mbformatbuf, lpOutputString, wcslen(lpOutputString)) == -1)
// if (wcstombs(mbformatbuf, lpOutputString, wcslen(lpOutputString)) == -1)
// strcpy(mbformatbuf, "XXX Unconvertable wide char detected in cDebug::DebugOut()\n");
vsprintf(buf, mbformatbuf, args);
@ -495,26 +495,26 @@ void cDebug::DebugOut( const wchar_t* lpOutputString, ... )
#if !USE_OUTPUT_DEBUG_STRING
#ifdef _DEBUG
TCERR << buf;
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(buf);
#endif // USE_OUTPUT_DEBUG_STRING
#endif // USE_OUTPUT_DEBUG_STRING
#else
char nbuf[1024];
#if IS_UNIX
strcpy(nbuf, buf);
strcpy(nbuf, buf);
#else
if (wcstombs(nbuf, buf, wcslen(buf)+1) == -1)
if (wcstombs(nbuf, buf, wcslen(buf)+1) == -1)
strcpy(nbuf, "XXX Unconvertable wide char detected in cDebug::DebugOut()\n");
#endif
#if !USE_OUTPUT_DEBUG_STRING
#ifdef _DEBUG
TCERR << nbuf;
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(nbuf);
#endif // USE_OUTPUT_DEBUG_STRING
#endif //_DEBUG
#else // USE_OUTPUT_DEBUG_STRING
::OutputDebugString(nbuf);
#endif // USE_OUTPUT_DEBUG_STRING
#endif
TCOUT.flush();

View File

@ -61,7 +61,7 @@
// When compiling with MFC, these are already defined and we get error msgs
// every time this file is included. Since these behave the same as the MFC
// version, it is OK to always undef them here....
// -- 20 Aug 99 mdb
// -- 20 Aug 99 mdb
//
#undef ASSERT
#undef TRACE
@ -78,90 +78,90 @@
class cDebug
{
public:
enum OutTarget
{
OUT_STDOUT = 1,
OUT_TRACE = 2,
OUT_FILE = 4
};
enum OutTarget
{
OUT_STDOUT = 1,
OUT_TRACE = 2,
OUT_FILE = 4
};
enum DebugLevel
{
D_ALWAYS = 0,
D_ERROR = 1,
D_WARNING = 4,
D_DEBUG = 8,
D_DETAIL = 16,
D_NEVER = 1000
};
enum DebugLevel
{
D_ALWAYS = 0,
D_ERROR = 1,
D_WARNING = 4,
D_DEBUG = 8,
D_DETAIL = 16,
D_NEVER = 1000
};
cDebug(const char* pLabel);
~cDebug();
cDebug(const cDebug& rhs);
cDebug(const char* pLabel);
~cDebug();
cDebug(const cDebug& rhs);
// These are the preferred tracing interfaces, because you don't need to know
// the DebugLevel enums.
// These are the preferred tracing interfaces, because you don't need to know
// the DebugLevel enums.
// Wide/Narrow Chars Issues: If you include a %s in your format string and you
// wish to print out a TCHAR (which might be a natural thing to do) you should
// encompas the format string with a _T("") macro, i.e. make it a TSTRING.
// The wide character overloads of these functions will expect wide strings
// for %s options.
//
void TraceAlways (const char *format, ...);
void TraceError (const char *format, ...);
void TraceWarning (const char *format, ...);
void TraceDebug (const char *format, ...);
void TraceDetail (const char *format, ...);
void TraceNever (const char *format, ...);
void TraceAlways (const wchar_t *format, ...);
void TraceError (const wchar_t *format, ...);
void TraceWarning (const wchar_t *format, ...);
void TraceDebug (const wchar_t *format, ...);
void TraceDetail (const wchar_t *format, ...);
void TraceNever (const wchar_t *format, ...);
void TraceAlways (const char *format, ...);
void TraceError (const char *format, ...);
void TraceWarning (const char *format, ...);
void TraceDebug (const char *format, ...);
void TraceDetail (const char *format, ...);
void TraceNever (const char *format, ...);
void TraceAlways (const wchar_t *format, ...);
void TraceError (const wchar_t *format, ...);
void TraceWarning (const wchar_t *format, ...);
void TraceDebug (const wchar_t *format, ...);
void TraceDetail (const wchar_t *format, ...);
void TraceNever (const wchar_t *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
void TraceVaArgs (int iDebugLevel, const char *format, va_list &args);
void TraceVaArgs (int iDebugLevel, const wchar_t *format, va_list &args);
void TraceVaArgs (int iDebugLevel, const char *format, va_list &args);
void TraceVaArgs (int iDebugLevel, const wchar_t *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, ...);
void Trace(int levelNum, const wchar_t* format, ...);
// Outputs based on levelnum. If levelnum <= global debug, print.
// Outputs based on levelnum. If levelnum <= global debug, print.
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 RemoveOutTarget (OutTarget target);
// used to specify the out target....
static bool HasOutTarget (OutTarget target);
static bool SetOutputFile (const char* filename);
// specifies the output file name used when OUT_FILE is set
static void SetDebugLevel (int level);
static int GetDebugLevel (void);
// gets and sets the global debug level. Trace output at or below this
// level will be output.
static void DebugOut ( const char* lpOutputString, ... );
static void DebugOut ( const wchar_t* 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
static bool SetOutputFile (const char* filename);
// specifies the output file name used when OUT_FILE is set
static void SetDebugLevel (int level);
static int GetDebugLevel (void);
// gets and sets the global debug level. Trace output at or below this
// level will be output.
static void DebugOut ( const char* lpOutputString, ... );
static void DebugOut ( const wchar_t* 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:
#ifdef DEBUG
enum { MAX_LABEL = 128 };
static int mDebugLevel;
static uint32 mOutMask;
static std::ofstream logfile;
char mLabel[MAX_LABEL];
static int mDebugLevel;
static uint32 mOutMask;
static std::ofstream logfile;
char mLabel[MAX_LABEL];
// helper functions
void DoTrace(const char *format, va_list &args);
void DoTrace(const wchar_t *format, va_list &args);
// helper functions
void DoTrace(const char *format, va_list &args);
void DoTrace(const wchar_t *format, va_list &args);
#endif
};
@ -180,12 +180,12 @@ private:
inline void cDebug::SetDebugLevel(int level)
{
mDebugLevel = level;
mDebugLevel = level;
}
inline int cDebug::GetDebugLevel()
{
return mDebugLevel;
return mDebugLevel;
}
#else // DEBUG
@ -193,30 +193,30 @@ inline int cDebug::GetDebugLevel()
inline cDebug::cDebug (const char *) {}
inline cDebug::~cDebug () {}
inline cDebug::cDebug (const cDebug&) {}
inline void cDebug::TraceAlways (const char *, ...) {}
inline void cDebug::TraceError (const char *, ...) {}
inline void cDebug::TraceWarning (const char *, ...) {}
inline void cDebug::TraceDebug (const char *, ...) {}
inline void cDebug::TraceDetail (const char *, ...) {}
inline void cDebug::TraceNever (const char *, ...) {}
inline void cDebug::TraceAlways (const wchar_t *, ...) {}
inline void cDebug::TraceError (const wchar_t *, ...) {}
inline void cDebug::TraceWarning (const wchar_t *, ...) {}
inline void cDebug::TraceDebug (const wchar_t *, ...) {}
inline void cDebug::TraceDetail (const wchar_t *, ...) {}
inline void cDebug::TraceNever (const wchar_t *, ...) {}
inline void cDebug::TraceVaArgs (int, const char *, va_list &) {}
inline void cDebug::TraceVaArgs (int, const wchar_t *, va_list &) {}
inline void cDebug::TraceAlways (const char *, ...) {}
inline void cDebug::TraceError (const char *, ...) {}
inline void cDebug::TraceWarning (const char *, ...) {}
inline void cDebug::TraceDebug (const char *, ...) {}
inline void cDebug::TraceDetail (const char *, ...) {}
inline void cDebug::TraceNever (const char *, ...) {}
inline void cDebug::TraceAlways (const wchar_t *, ...) {}
inline void cDebug::TraceError (const wchar_t *, ...) {}
inline void cDebug::TraceWarning (const wchar_t *, ...) {}
inline void cDebug::TraceDebug (const wchar_t *, ...) {}
inline void cDebug::TraceDetail (const wchar_t *, ...) {}
inline void cDebug::TraceNever (const wchar_t *, ...) {}
inline void cDebug::TraceVaArgs (int, const char *, va_list &) {}
inline void cDebug::TraceVaArgs (int, const wchar_t *, va_list &) {}
inline void cDebug::Trace (int, const char*, ...) {}
inline void cDebug::Trace (int, const wchar_t*, ...) {}
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*, ... ) {}
inline void cDebug::DebugOut ( const wchar_t*, ... ) {}
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*, ... ) {}
inline void cDebug::DebugOut ( const wchar_t*, ... ) {}
#endif // DEBUG
@ -229,9 +229,9 @@ inline void cDebug::DebugOut ( const wchar_t*, ... ) {}
#if IS_UNIX
#define ASSERTMSG( exp, s ) assert( (exp) != 0 )
#define ASSERT( exp ) assert( (exp) != 0 )
// if we are not windows we will just use the standard assert()
#define ASSERTMSG( exp, s ) assert( (exp) != 0 )
#define ASSERT( exp ) assert( (exp) != 0 )
// if we are not windows we will just use the standard assert()
#define TSS_DebugBreak() ASSERT( false );
#endif// IS_UNIX

View File

@ -1,90 +0,0 @@
//
// The developer of the original code and/or files is Tripwire, Inc.
// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire,
// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights
// reserved.
//
// This program is free software. The contents of this file are subject
// to the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. You may redistribute it and/or modify it
// only in compliance with the GNU General Public License.
//
// This program is distributed in the hope that it will be useful.
// However, this program is distributed AS-IS WITHOUT ANY
// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// Nothing in the GNU General Public License or any other license to use
// the code or files shall permit you to use Tripwire's trademarks,
// service marks, or other intellectual property without Tripwire's
// prior written consent.
//
// If you have any questions, please contact Tripwire, Inc. at either
// info@tripwire.org or www.tripwire.org.
//
// debug_t -- debug component test driver
#include "stdcore.h"
#include "debug.h"
#include "test/test.h"
void TestDebug()
{
// it is amusing that we use cDebug to output the results of testing cDebug
// "Are you insane?" ... "No, I am not."
cDebug d("TestDebug()");
d.TraceDebug("Entering...");
// save the current debug level, since we will be altering it.
int oldDebugLevel = cDebug::GetDebugLevel();
// test debug level variation...
d.TraceDebug("Setting debug level to Debug(%d)\n", cDebug::D_DEBUG);
cDebug::SetDebugLevel(cDebug::D_DEBUG);
d.TraceDebug ("You should see this, as well as line 2 below, but not line 3.\n");
d.TraceWarning ("Line 2: Warning(%d)\n", cDebug::D_WARNING);
d.TraceDetail ("Line 3: Detail(%d)\n", cDebug::D_DETAIL);
d.TraceDebug ("Restoring the debug level to %d\n", oldDebugLevel);
cDebug::SetDebugLevel(oldDebugLevel);
// testing the output source
int oldOutTarget = 0;
if(cDebug::HasOutTarget(cDebug::OUT_STDOUT)) oldOutTarget |= cDebug::OUT_STDOUT;
if(cDebug::HasOutTarget(cDebug::OUT_TRACE)) oldOutTarget |= cDebug::OUT_TRACE;
if(cDebug::HasOutTarget(cDebug::OUT_FILE)) oldOutTarget |= cDebug::OUT_FILE;
cDebug::RemoveOutTarget(cDebug::OUT_STDOUT);
cDebug::RemoveOutTarget(cDebug::OUT_TRACE);
cDebug::RemoveOutTarget(cDebug::OUT_FILE);
d.TraceDebug("You should not see this (All out targets removed)\n");
cDebug::AddOutTarget(cDebug::OUT_STDOUT);
d.TraceDebug("You should see this in stdout only.\n");
cDebug::AddOutTarget(cDebug::OUT_TRACE);
d.TraceDebug("You should see this in stdout and trace.\n");
cDebug::RemoveOutTarget(cDebug::OUT_STDOUT);
d.TraceDebug("You should see this in trace only.\n");
// set up an output file...use the temp file in test.h
std::string str = TEMP_DIR_N;
str += "/debug.out";
bool bResult = false;
bResult = cDebug::SetOutputFile(str.c_str());
TEST(bResult);
d.TraceDebug("This should be in trace and the file %s.\n", str.c_str());
// restore the out source...
// TODO -- note that the original output file cannot be restored; this sucks!
if(oldOutTarget & cDebug::OUT_STDOUT) cDebug::AddOutTarget(cDebug::OUT_STDOUT); else cDebug::RemoveOutTarget(cDebug::OUT_STDOUT);
if(oldOutTarget & cDebug::OUT_TRACE) cDebug::AddOutTarget(cDebug::OUT_TRACE); else cDebug::RemoveOutTarget(cDebug::OUT_TRACE);
if(oldOutTarget & cDebug::OUT_FILE) cDebug::AddOutTarget(cDebug::OUT_FILE); else cDebug::RemoveOutTarget(cDebug::OUT_FILE);
d.TraceDebug("Exiting...\n");
}

View File

@ -829,7 +829,7 @@ bool cEncoder::OnlyOneCatagoryPerChar() const
ach[0] = ch;
for( sack_type::const_iterator atE = m_encodings.begin(); atE != m_encodings.end(); atE++ )
{
if( (*atE)->NeedsEncoding( ach.begin(), ach.end() ) )
if( (*atE)->NeedsEncoding( ach.begin(), ach.end() ) )
{
if( fFailedATest )
return false; // each char can only fail one test

View File

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

View File

@ -43,55 +43,55 @@ class eError
{
public:
//-------------------------------------------------------------------------
// Construction and Assignment
//-------------------------------------------------------------------------
eError( const TSTRING& msg, uint32 flags = 0 );
explicit eError( const eError& rhs );
explicit eError();
void operator=( const eError& rhs );
//-------------------------------------------------------------------------
// Construction and Assignment
//-------------------------------------------------------------------------
eError( const TSTRING& msg, uint32 flags = 0 );
explicit eError( const eError& rhs );
explicit eError();
void operator=( const eError& rhs );
//-------------------------------------------------------------------------
// Destruction
//-------------------------------------------------------------------------
virtual ~eError();
//-------------------------------------------------------------------------
// Destruction
//-------------------------------------------------------------------------
virtual ~eError();
//-------------------------------------------------------------------------
// Data Access
//-------------------------------------------------------------------------
virtual uint32 GetID() const = 0;
// returns a system wide unique identifier for this exception. See the
// macro below for the typical implementation of this method.
// This is used to associate the error with a string description of the
// error via the global error table.
//-------------------------------------------------------------------------
// Data Access
//-------------------------------------------------------------------------
virtual uint32 GetID() const = 0;
// returns a system wide unique identifier for this exception. See the
// macro below for the typical implementation of this method.
// This is used to associate the error with a string description of the
// error via the global error table.
virtual TSTRING GetMsg() const;
// returns specific information about the error that occured. Provides
// additional information about the error described by GetID(). It should
// not provide any information redundant with GetID().
//
virtual TSTRING GetMsg() const;
// returns specific information about the error that occured. Provides
// additional information about the error described by GetID(). It should
// not provide any information redundant with GetID().
//
// The string passed to the constructor should be formated properly to
// be displayed as the "Second" part of an error message, or the derived
// class should override GetMsg() and return a string appropriate for display.
uint32 GetFlags() const;
// Flags are defined below. Currently, these only have an impact on how errors are
// displayed.
uint32 GetFlags() const;
// Flags are defined below. Currently, these only have an impact on how errors are
// displayed.
//-------------------------------------------------------------------------
// Flags
//-------------------------------------------------------------------------
enum Flag
{
NON_FATAL = 0x00000001, // displays "Error" or "Warning" ?
SUPRESS_THIRD_MSG = 0x00000002 // supresses the "continuing" or "exiting" message
};
//-------------------------------------------------------------------------
// Flags
//-------------------------------------------------------------------------
enum Flag
{
NON_FATAL = 0x00000001, // displays "Error" or "Warning" ?
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);
bool IsFatal() const;
// Fatality is set to true by default when eError is constructed. But when an error
@ -101,19 +101,19 @@ public:
void SetSupressThird(bool supressThird);
bool SupressThird() const;
//-------------------------------------------------------------------------
// Utility Methods
//-------------------------------------------------------------------------
static uint32 CalcHash( const char* name );
// 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
// for errors.
//-------------------------------------------------------------------------
// Utility Methods
//-------------------------------------------------------------------------
static uint32 CalcHash( const char* name );
// 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
// for errors.
//-------------------------------------------------------------------------
// Private Implementation
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Private Implementation
//-------------------------------------------------------------------------
protected:
TSTRING mMsg;
TSTRING mMsg;
uint32 mFlags;
};
@ -125,7 +125,7 @@ protected:
// TSS_BEGIN_EXCEPTION / TSS_END_EXCEPTION
//
// Serves the same purpose as TSS_EXCEPTION but allows custom data and methods
// to be added to the exception class.
// to be added to the exception class.
///////////////////////////////////////////////////////////////////////////////
#if HAVE_GCC
@ -135,22 +135,22 @@ protected:
#endif
#define TSS_BEGIN_EXCEPTION( except, base ) \
class except : public base \
{\
public:\
except( const TSTRING& msg, uint32 flags = 0 ) \
: base( msg, flags ) {} \
TSS_BEGIN_EXCEPTION_EXPLICIT except( const except& rhs ) \
: base( rhs ) {} \
explicit except() : base() {} \
\
virtual uint32 GetID() const \
{\
return CalcHash( #except ); \
}\
class except : public base \
{\
public:\
except( const TSTRING& msg, uint32 flags = 0 ) \
: base( msg, flags ) {} \
TSS_BEGIN_EXCEPTION_EXPLICIT except( const except& rhs ) \
: base( rhs ) {} \
explicit except() : base() {} \
\
virtual uint32 GetID() const \
{\
return CalcHash( #except ); \
}\
#define TSS_END_EXCEPTION( ) \
};
};
///////////////////////////////////////////////////////////////////////////////
// TSS_BEGIN_EXCEPTION_NO_CTOR
@ -158,29 +158,29 @@ protected:
// Same as TSS_BEGIN_EXCEPTION, but doesn't define any ctors.
///////////////////////////////////////////////////////////////////////////////
#define TSS_BEGIN_EXCEPTION_NO_CTOR( except, base ) \
class except : public base \
{\
public:\
explicit except() : base() {} \
\
virtual uint32 GetID() const \
{\
return CalcHash( #except ); \
}\
class except : public base \
{\
public:\
explicit except() : base() {} \
\
virtual uint32 GetID() const \
{\
return CalcHash( #except ); \
}\
///////////////////////////////////////////////////////////////////////////////
// TSS_EXCEPTION
//
// This is a convenience define for quickly defining an exception class. After
// defining a new exception, don't forget to add it to the package's error
// string file!
// This is a convenience define for quickly defining an exception class. After
// defining a new exception, don't forget to add it to the package's error
// string file!
//
// 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 ) \
TSS_BEGIN_EXCEPTION( except, base ) \
TSS_END_EXCEPTION()
TSS_BEGIN_EXCEPTION( except, base ) \
TSS_END_EXCEPTION()
//-----------------------------------------------------------------------------
// Inline Implementation
@ -190,30 +190,30 @@ protected:
// eError
///////////////////////////////////////////////////////////////////////////////
inline eError::eError( const TSTRING& msg, uint32 flags )
: mMsg ( msg ),
mFlags ( flags )
: mMsg ( msg ),
mFlags ( flags )
{
}
///////////////////////////////////////////////////////////////////////////////
// eError
///////////////////////////////////////////////////////////////////////////////
inline eError::eError( const eError& rhs )
: mMsg ( rhs.mMsg ),
mFlags ( rhs.mFlags )
: mMsg ( rhs.mMsg ),
mFlags ( rhs.mFlags )
{
}
///////////////////////////////////////////////////////////////////////////////
// eError
///////////////////////////////////////////////////////////////////////////////
inline eError::eError( )
: mMsg ( _T("") ),
mFlags ( 0 )
: mMsg ( _T("") ),
mFlags ( 0 )
{
}
@ -222,8 +222,8 @@ inline eError::eError( )
///////////////////////////////////////////////////////////////////////////////
inline void eError::operator=( const eError& rhs )
{
mMsg = rhs.mMsg;
mFlags = rhs.mFlags;
mMsg = rhs.mMsg;
mFlags = rhs.mFlags;
}
///////////////////////////////////////////////////////////////////////////////
@ -231,7 +231,7 @@ inline void eError::operator=( const eError& rhs )
///////////////////////////////////////////////////////////////////////////////
inline eError::~eError()
{
}
///////////////////////////////////////////////////////////////////////////////
@ -239,7 +239,7 @@ inline eError::~eError()
///////////////////////////////////////////////////////////////////////////////
inline TSTRING eError::GetMsg() const
{
return mMsg;
return mMsg;
}
///////////////////////////////////////////////////////////////////////////////
@ -247,7 +247,7 @@ inline TSTRING eError::GetMsg() const
///////////////////////////////////////////////////////////////////////////////
inline uint32 eError::GetFlags() const
{
return mFlags;
return mFlags;
}
///////////////////////////////////////////////////////////////////////////////
@ -255,7 +255,7 @@ inline uint32 eError::GetFlags() const
///////////////////////////////////////////////////////////////////////////////
inline void eError::SetFlags( uint32 flags )
{
mFlags = flags;
mFlags = flags;
}
///////////////////////////////////////////////////////////////////////////////

View File

@ -47,32 +47,32 @@ class eError;
///////////////////////////////////////////////////////////////////////////////
// cErrorBucket -- contains an interface that handles error reporting, and
// contains a link to a child bucket. Each concrete implementation of the
// cErrorBucket interface will perform its own specific task related to the
// error's occurence (print to stderr, store in a queue, etc) and then forward
// the error on to its child link. The parent bucket does not own the destruction
// of the pointer to the child bucket.
// contains a link to a child bucket. Each concrete implementation of the
// cErrorBucket interface will perform its own specific task related to the
// error's occurence (print to stderr, store in a queue, etc) and then forward
// the error on to its child link. The parent bucket does not own the destruction
// of the pointer to the child bucket.
///////////////////////////////////////////////////////////////////////////////
class cErrorBucket
{
public:
cErrorBucket();
virtual ~cErrorBucket() {}
cErrorBucket();
virtual ~cErrorBucket() {}
virtual void AddError(const eError& error);
// add an error to the bucket
virtual void AddError(const eError& error);
// add an error to the bucket
cErrorBucket* GetChild();
// returns the bucket that the current bucket is chained to, or
// NULL if nothing is attached to it.
cErrorBucket* SetChild(cErrorBucket* pNewChild);
// sets the child link of this bucket; returns the old link value
cErrorBucket* GetChild();
// returns the bucket that the current bucket is chained to, or
// NULL if nothing is attached to it.
cErrorBucket* SetChild(cErrorBucket* pNewChild);
// sets the child link of this bucket; returns the old link value
protected:
virtual void HandleError(const eError& error) = 0;
// override this to implement error handling functionality specific to
// the derived class
cErrorBucket* mpChild;
virtual void HandleError(const eError& error) = 0;
// override this to implement error handling functionality specific to
// the derived class
cErrorBucket* mpChild;
};
//#############################################################################
@ -82,20 +82,20 @@ protected:
// cErrorBucket
///////////////////
inline cErrorBucket::cErrorBucket() :
mpChild(0)
mpChild(0)
{
}
inline cErrorBucket* cErrorBucket::GetChild()
{
return mpChild;
return mpChild;
}
inline cErrorBucket* cErrorBucket::SetChild(cErrorBucket* pNewChild)
{
cErrorBucket* pOldChild = mpChild;
mpChild = pNewChild;
return pOldChild;
cErrorBucket* pOldChild = mpChild;
mpChild = pNewChild;
return pOldChild;
}
#endif

View File

@ -42,9 +42,9 @@
//#############################################################################
void cErrorBucket::AddError(const eError& error)
{
HandleError(error);
if(mpChild)
mpChild->AddError(error);
HandleError(error);
if(mpChild)
mpChild->AddError(error);
}
//#############################################################################
@ -55,14 +55,14 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
cDisplayEncoder e(
(cDisplayEncoder::Flags) ( cDisplayEncoder::NON_ROUNDTRIP |
cDisplayEncoder::ALLOW_WHITESPACE ) );
TSTRING errStr;
TSTRING errStr;
//
// if the ID is zero, just return.
// this should only occur at the top level of a program (ie -- twcmdline.cpp) and
// indicates that an error occurred and an error message has already been printed out.
// Therefore, we will do nothing here but return.
//
//
// if the ID is zero, just return.
// this should only occur at the top level of a program (ie -- twcmdline.cpp) and
// indicates that an error occurred and an error message has already been printed out.
// Therefore, we will do nothing here but return.
//
// TODO: Having an error with an ID of 0 is legacy. The only place it happens at this
// point is when we throw ePoly() with no constructor arguments. At some point we want
@ -70,8 +70,8 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
// 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 );
if( error.GetID() == 0 )
return;
if( error.GetID() == 0 )
return;
// "First Part" header
errStr = TSS_GetString( cCore, error.IsFatal() ? core::STR_ERROR_ERROR
@ -94,7 +94,7 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
// #pragma message("errorbucketimpl.cpp needs a little help in the mb arena, with the findfirst/last and such")
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
// second part. This was added to allow specifing a verbose string as the second part
@ -109,7 +109,7 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
ASSERT(errStr.length() + len + 6 < 80); // line too big for terminal?
// Add 6 to account for "### ' and ': '
TCERR << TSS_GetString( cCore, core::STR_ERROR_COLON ) << _T(" ") << errStr;
TCERR << std::endl;
TCERR << std::endl;
}
// "Second Part" error string
@ -160,22 +160,22 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
}
// "Third Part" print 'exiting' or 'continuing'
// note that we supress this part if the appropriate flag is set...
//
if( (error.GetFlags() & eError::SUPRESS_THIRD_MSG) == 0 )
{
// note that we supress this part if the appropriate flag is set...
//
if( (error.GetFlags() & eError::SUPRESS_THIRD_MSG) == 0 )
{
TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER)
<< TSS_GetString(
<< TSS_GetString(
cCore,
error.IsFatal()
? core::STR_ERROR_EXITING
: core::STR_ERROR_CONTINUING ) << std::endl;
}
}
}
void cErrorReporter::HandleError(const eError& error)
{
PrintErrorMsg(error);
PrintErrorMsg(error);
}
//#############################################################################
@ -183,11 +183,11 @@ void cErrorReporter::HandleError(const eError& error)
//#############################################################################
void cErrorTracer::HandleError(const eError& error)
{
cDebug d("cErrorTracer::HandleError");
cDebug d("cErrorTracer::HandleError");
d.TraceError( _T("%s : %s\n"),
cErrorTable::GetInstance()->Get( error.GetID() ).c_str(),
error.GetMsg().c_str() );
d.TraceError( _T("%s : %s\n"),
cErrorTable::GetInstance()->Get( error.GetID() ).c_str(),
error.GetMsg().c_str() );
}
//#############################################################################
@ -197,51 +197,51 @@ IMPLEMENT_TYPEDSERIALIZABLE(cErrorQueue, _T("cErrorQueue"), 0, 1);
void cErrorQueue::Clear()
{
mList.clear();
mList.clear();
}
int cErrorQueue::GetNumErrors() const
{
return mList.size();
return mList.size();
}
void cErrorQueue::HandleError(const eError& error)
{
mList.push_back( ePoly( error ) );
mList.push_back( ePoly( error ) );
}
cErrorQueueIter::cErrorQueueIter(cErrorQueue& queue) :
mList(queue.mList)
mList(queue.mList)
{
SeekBegin();
SeekBegin();
}
cErrorQueueIter::cErrorQueueIter(const cErrorQueue& queue)
: mList( ((cErrorQueue*)&queue)->mList )
: mList( ((cErrorQueue*)&queue)->mList )
{
SeekBegin();
SeekBegin();
}
void cErrorQueueIter::SeekBegin()
{
mIter = mList.begin();
mIter = mList.begin();
}
void cErrorQueueIter::Next()
{
++mIter;
++mIter;
}
bool cErrorQueueIter::Done() const
{
return (mIter == mList.end());
return (mIter == mList.end());
}
const ePoly& cErrorQueueIter::GetError() const
{
ASSERT(! Done());
return (*mIter);
ASSERT(! Done());
return (*mIter);
}
///////////////////////////////////////////////////////////////////////////////
@ -249,25 +249,25 @@ const ePoly& cErrorQueueIter::GetError() const
///////////////////////////////////////////////////////////////////////////////
void cErrorQueue::Read(iSerializer* pSerializer, int32 version)
{
if (version > Version())
ThrowAndAssert(eSerializerVersionMismatch(_T("ErrorQueue Read")));
if (version > Version())
ThrowAndAssert(eSerializerVersionMismatch(_T("ErrorQueue Read")));
int32 size;
mList.clear();
pSerializer->ReadInt32(size);
for(int i = 0; i < size; ++i)
{
int32 size;
mList.clear();
pSerializer->ReadInt32(size);
for(int i = 0; i < size; ++i)
{
int32 errorNumber;
TSTRING errorString;
int32 flags;
pSerializer->ReadInt32 (errorNumber);
pSerializer->ReadString (errorString);
pSerializer->ReadInt32 (flags);
pSerializer->ReadInt32 (errorNumber);
pSerializer->ReadString (errorString);
pSerializer->ReadInt32 (flags);
mList.push_back( ePoly( errorNumber, errorString, flags ) );
}
mList.push_back( ePoly( errorNumber, errorString, flags ) );
}
}
///////////////////////////////////////////////////////////////////////////////
@ -275,15 +275,15 @@ void cErrorQueue::Read(iSerializer* pSerializer, int32 version)
///////////////////////////////////////////////////////////////////////////////
void cErrorQueue::Write(iSerializer* pSerializer) const
{
pSerializer->WriteInt32(mList.size());
ListType::const_iterator i;
for( i = mList.begin(); i != mList.end(); ++i)
{
pSerializer->WriteInt32 ((*i).GetID());
pSerializer->WriteString((*i).GetMsg());
pSerializer->WriteInt32 ((*i).GetFlags());
}
pSerializer->WriteInt32(mList.size());
ListType::const_iterator i;
for( i = mList.begin(); i != mList.end(); ++i)
{
pSerializer->WriteInt32 ((*i).GetID());
pSerializer->WriteString((*i).GetMsg());
pSerializer->WriteInt32 ((*i).GetFlags());
}
}
@ -292,15 +292,15 @@ void cErrorQueue::Write(iSerializer* pSerializer) const
///////////////////////////////////////////////////////////////////////////////
void cErrorQueue::TraceContents(int dl) const
{
if(dl < 0)
dl = cDebug::D_DEBUG;
cDebug d("cFCOErrorQueue::TraceContents");
ListType::const_iterator i;
int counter = 0;
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());
}
if(dl < 0)
dl = cDebug::D_DEBUG;
cDebug d("cFCOErrorQueue::TraceContents");
ListType::const_iterator i;
int counter = 0;
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());
}
}

View File

@ -61,111 +61,111 @@
//////////////////////////////////////////////////////
// cErrorReporter -- sends all error messages to
// stderr
// stderr
//////////////////////////////////////////////////////
class cErrorReporter : public cErrorBucket
{
public:
static void PrintErrorMsg(const eError& error, const TSTRING& strExtra = _T(""));
// function that HandleError() uses to print the error messages to stderr.
// this function uses the current authoritative format for error reporting, so
// other functions needing to display errors to the user should use this.
//
static void PrintErrorMsg(const eError& error, const TSTRING& strExtra = _T(""));
// function that HandleError() uses to print the error messages to stderr.
// this function uses the current authoritative format for error reporting, so
// 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: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
// occurred.
// 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
// occurred.
protected:
virtual void HandleError(const eError& error);
virtual void HandleError(const eError& error);
};
///////////////////////////////////////////////////////
// cErrorTracer -- traces all errors with the D_ERROR debug
// level
// level
///////////////////////////////////////////////////////
class cErrorTracer : public cErrorBucket
{
protected:
virtual void HandleError(const eError& error);
virtual void HandleError(const eError& error);
};
//////////////////////////////////////////////////////
// cErrorQueue -- keeps track of all the errors that
// are reported to it, providing an interface for
// retrieving them at a later time
// are reported to it, providing an interface for
// retrieving them at a later time
//////////////////////////////////////////////////////
class cErrorQueue : public cErrorBucket, public iTypedSerializable
{
friend class cErrorQueueIter;
friend class cErrorQueueIter;
public:
void Clear();
// remove all errors from the queue
int GetNumErrors() const;
// returns how many errors are in the queue
void Clear();
// remove all errors from the queue
int GetNumErrors() const;
// returns how many errors are in the queue
//
// iSerializable interface
//
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
//
// iSerializable interface
//
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
//
// Debugging
//
void TraceContents(int dl = -1) const;
//
// Debugging
//
void TraceContents(int dl = -1) const;
protected:
virtual void HandleError(const eError& error);
virtual void HandleError(const eError& error);
private:
typedef std::list<ePoly> ListType;
ListType mList;
typedef std::list<ePoly> ListType;
ListType mList;
DECLARE_TYPEDSERIALIZABLE()
DECLARE_TYPEDSERIALIZABLE()
};
class cErrorQueueIter
{
public:
cErrorQueueIter(cErrorQueue& queue);
cErrorQueueIter(const cErrorQueue& queue);
~cErrorQueueIter() {}
cErrorQueueIter(cErrorQueue& queue);
cErrorQueueIter(const cErrorQueue& queue);
~cErrorQueueIter() {}
// iteration methods
void SeekBegin();
void Next();
bool Done() const;
// iteration methods
void SeekBegin();
void Next();
bool Done() const;
// access to the error
const ePoly& GetError() const;
// both of these return results are undefined if the iterator
// is not valid (ie - IsDone() == true)
// access to the error
const ePoly& GetError() const;
// both of these return results are undefined if the iterator
// is not valid (ie - IsDone() == true)
private:
cErrorQueue::ListType& mList;
cErrorQueue::ListType::iterator mIter;
cErrorQueue::ListType& mList;
cErrorQueue::ListType::iterator mIter;
};
//////////////////////////////////////////////////////
// cErrorBucketNull -- an error bucket that plays the
// role of /dev/null
// role of /dev/null
//////////////////////////////////////////////////////
class cErrorBucketNull : public cErrorBucket
{
virtual void AddError(const eError& ) {}
virtual void AddError(const eError& ) {}
protected:
virtual void HandleError(const eError& ) {}
virtual void HandleError(const eError& ) {}
};
//////////////////////////////////////////////////////
// cErrorBucketPassThru -- does nothing with errors;
// just passes them on to its children
// just passes them on to its children
//////////////////////////////////////////////////////
class cErrorBucketPassThru : public cErrorBucket
{
protected:
virtual void HandleError(const eError& ) {}
virtual void HandleError(const eError& ) {}
};

View File

@ -45,8 +45,8 @@
///////////////////////////////////////////////////////////////////////////////
cErrorTable* cErrorTable::GetInstance()
{
static cErrorTable gErrorTable;
return &gErrorTable;
static cErrorTable gErrorTable;
return &gErrorTable;
}
///////////////////////////////////////////////////////////////////////////////

View File

@ -34,8 +34,8 @@
// Date: 30 April 99
// Creator: mdb
//
// cErrorTable -- singleton derived from Resource_<> that serves as the global
// error id to string mapping
// cErrorTable -- singleton derived from Resource_<> that serves as the global
// error id to string mapping
//
#ifndef __ERRORTABLE_H
#define __ERRORTABLE_H
@ -54,16 +54,16 @@ class eError;
class cErrorTable : public cMessages_<uint32, TCHAR>
{
public:
typedef cMessages_<uint32, TCHAR> inherited;
typedef cMessages_<uint32, TCHAR> inherited;
//
// Convenience Methods
//
void Put( const eError& e, const TCHAR* msg );
//
// Singleton Interface
//
static cErrorTable* GetInstance();
//
// Convenience Methods
//
void Put( const eError& e, const TCHAR* msg );
//
// Singleton Interface
//
static cErrorTable* GetInstance();
private:
#ifdef _DEBUG
@ -85,55 +85,55 @@ inline void cErrorTable::Put( const eError& e, const TCHAR* msg )
//-----------------------------------------------------------------------------
//
// These macros make it easy for a module to register errors with the global
// error table. Them like this:
// error table. Them like this:
//
// // animalerrors.h
// //
// TSS_DECLARE_ERROR_REGISTRATION( animal )
// // animalerrors.h
// //
// TSS_DECLARE_ERROR_REGISTRATION( animal )
//
// // animalerrors.cpp
// //
// TSS_BEGIN_ERROR_REGISTRATION( animal )
// TSS_REGISTER_ERROR( eDog, _T("Dog error") )
// TSS_REGISTER_ERROR( eDogBark, _T("Barking error") )
// TSS_END_ERROR_REGISTRATION()
// // animalerrors.cpp
// //
// TSS_BEGIN_ERROR_REGISTRATION( animal )
// TSS_REGISTER_ERROR( eDog, _T("Dog error") )
// TSS_REGISTER_ERROR( eDogBark, _T("Barking error") )
// TSS_END_ERROR_REGISTRATION()
//
// // pkg.h
// TSS_DeclarePackage( cWorld )
// // pkg.h
// TSS_DeclarePackage( cWorld )
//
// // pkg.cpp
// cWorld::cWorld()
// {
// TSS_REGISTER_PKG_ERRORS( animal )
// // pkg.cpp
// cWorld::cWorld()
// {
// TSS_REGISTER_PKG_ERRORS( animal )
//
//===================
// cpp file macros
//===================
#define TSS_BEGIN_ERROR_REGISTRATION( pkgName ) \
RegisterErrors##pkgName::RegisterErrors##pkgName() \
{
RegisterErrors##pkgName::RegisterErrors##pkgName() \
{
#define TSS_REGISTER_ERROR( err, str ) \
cErrorTable::GetInstance()->Put \
( err, str );
cErrorTable::GetInstance()->Put \
( err, str );
#define TSS_END_ERROR_REGISTRATION() \
}
}
//===================
// h file macros
//===================
#define TSS_DECLARE_ERROR_REGISTRATION( pkgName ) \
struct RegisterErrors##pkgName \
{\
RegisterErrors##pkgName(); \
};
struct RegisterErrors##pkgName \
{\
RegisterErrors##pkgName(); \
};
//===================
// package init macros
//===================
#define TSS_REGISTER_PKG_ERRORS( pkgName ) \
RegisterErrors##pkgName register##pkgName;
RegisterErrors##pkgName register##pkgName;
#endif //__ERRORTABLE_H

16
src/core/errorutil.cpp Executable file → Normal file
View File

@ -43,11 +43,11 @@
#if IS_UNIX
namespace //unique
{
TCHAR* tw_itot( int value, TCHAR* string, int radix)
{
_stprintf( string, "%d", value );
return string;
}
TCHAR* tw_itot( int value, TCHAR* string, int radix)
{
_stprintf( string, "%d", value );
return string;
}
}
#else
#define tw_itot _itot
@ -73,7 +73,7 @@ eInternal::eInternal(TCHAR* sourceFile, int lineNum)
///////////////////////////////////////////////////////////////////////////////
TSTRING cErrorUtil::MakeFileError( const TSTRING& msg, const TSTRING& fileName )
{
TSTRING ret;
TSTRING ret;
ret = TSS_GetString( cCore, core::STR_ERR2_FILENAME );
ret.append( fileName );
ret.append( 1, _T('\n') );
@ -82,7 +82,7 @@ TSTRING cErrorUtil::MakeFileError( const TSTRING& msg, const TSTRING& fileName )
{
ret.append(msg);
}
return ret;
return ret;
}

View File

@ -36,10 +36,10 @@
// Company: TSS
// Desc: contains useful eError derived classes
//
// eInternal -- internal logic errors ( ie -- programming mistakes )
// ePoly -- "polymorphic" error that takes its ID as input instead
// of from its class name
// ThrowAndAssert -- asserts false and throws the specified exception
// eInternal -- internal logic errors ( ie -- programming mistakes )
// ePoly -- "polymorphic" error that takes its ID as input instead
// of from its class name
// ThrowAndAssert -- asserts false and throws the specified exception
//
#ifndef __ERRORUTIL_H
#define __ERRORUTIL_H
@ -55,22 +55,22 @@
class ePoly : public eError
{
public:
//-------------------------------------------------------------------------
// Construction and Assignment
//-------------------------------------------------------------------------
ePoly( uint32 id, const TSTRING& msg, uint32 flags = 0 );
explicit ePoly( const eError& rhs );
explicit ePoly();
void operator=( const eError& rhs );
//-------------------------------------------------------------------------
// Construction and Assignment
//-------------------------------------------------------------------------
ePoly( uint32 id, const TSTRING& msg, uint32 flags = 0 );
explicit ePoly( const eError& rhs );
explicit ePoly();
void operator=( const eError& rhs );
//-------------------------------------------------------------------------
// ID manipulation
//-------------------------------------------------------------------------
virtual uint32 GetID() const;
void SetID( uint32 id );
//-------------------------------------------------------------------------
// ID manipulation
//-------------------------------------------------------------------------
virtual uint32 GetID() const;
void SetID( uint32 id );
private:
uint32 mID;
uint32 mID;
};
//-----------------------------------------------------------------------------
@ -78,7 +78,7 @@ private:
//-----------------------------------------------------------------------------
TSS_BEGIN_EXCEPTION( eInternal, eError )
public:
eInternal( TCHAR* file, int lineNum );
eInternal( TCHAR* file, int lineNum );
TSS_END_EXCEPTION()
//-----------------------------------------------------------------------------
@ -87,11 +87,11 @@ TSS_END_EXCEPTION()
class cErrorUtil
{
public:
static TSTRING MakeFileError( const TSTRING& msg, const TSTRING& fileName );
// constructs an error message of the form:
// File: <fileName> \n <msg>
// This is useful for constructing strings to pass as the msg parameter
// to eError constructors.
static TSTRING MakeFileError( const TSTRING& msg, const TSTRING& fileName );
// constructs an error message of the form:
// File: <fileName> \n <msg>
// This is useful for constructing strings to pass as the msg parameter
// to eError constructors.
};
//-----------------------------------------------------------------------------
@ -99,15 +99,15 @@ public:
//-----------------------------------------------------------------------------
//
// NOTE -- we require the developer to supply the file name instead of using
// __FILE__ because that includes the full path to the file, which we
// would not like to display to the user.
// __FILE__ because that includes the full path to the file, which we
// would not like to display to the user.
//
#define INTERNAL_ERROR(filename) eInternal((TCHAR*)_T(filename), __LINE__)
#define THROW_INTERNAL(filename) throw eInternal((TCHAR*)_T(filename), __LINE__)
#define INTERNAL_ERROR(filename) 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
// 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; }
@ -119,10 +119,10 @@ public:
// ePoly
///////////////////////////////////////////////////////////////////////////////
inline ePoly::ePoly( uint32 id, const TSTRING& msg, uint32 flags )
: eError( msg, flags ),
mID( id )
: eError( msg, flags ),
mID( id )
{
}
///////////////////////////////////////////////////////////////////////////////
@ -137,10 +137,10 @@ inline ePoly::ePoly( const eError& rhs )
// ePoly
///////////////////////////////////////////////////////////////////////////////
inline ePoly::ePoly()
: eError( _T("") ),
mID( 0 )
: eError( _T("") ),
mID( 0 )
{
}
///////////////////////////////////////////////////////////////////////////////
@ -150,7 +150,7 @@ inline void ePoly::operator=( const eError& rhs )
{
mMsg = rhs.GetMsg();
mFlags = rhs.GetFlags();
mID = rhs.GetID();
mID = rhs.GetID();
}
///////////////////////////////////////////////////////////////////////////////
@ -158,7 +158,7 @@ inline void ePoly::operator=( const eError& rhs )
///////////////////////////////////////////////////////////////////////////////
inline uint32 ePoly::GetID() const
{
return mID;
return mID;
}
///////////////////////////////////////////////////////////////////////////////
@ -166,7 +166,7 @@ inline uint32 ePoly::GetID() const
///////////////////////////////////////////////////////////////////////////////
inline void ePoly::SetID( uint32 id )
{
mID = id;
mID = id;
}
#endif //__ERRORUTIL_H

112
src/core/file.h Executable file → Normal file
View File

@ -30,7 +30,7 @@
// info@tripwire.org or www.tripwire.org.
//
// file.h : Interface for cFile class, which abstracts file operations across
// different platforms (currently just Windows and Unix...)
// different platforms (currently just Windows and Unix...)
#ifndef __FILE_H
#define __FILE_H
@ -55,17 +55,17 @@
// eFile exception class
//=============================================================================
TSS_FILE_EXCEPTION( eFile, eFileError );
TSS_FILE_EXCEPTION( eFileOpen, eFile );
TSS_FILE_EXCEPTION( eFileWrite, eFile );
TSS_FILE_EXCEPTION( eFileRead, eFile );
TSS_FILE_EXCEPTION( eFileEOF, eFile ); // never used!
TSS_FILE_EXCEPTION( eFileSeek, eFile );
TSS_FILE_EXCEPTION( eFileInvalidOp, eFile ); // never used!
TSS_FILE_EXCEPTION( eFileTrunc, eFile );
TSS_FILE_EXCEPTION( eFileClose, eFile ); // never used!
TSS_FILE_EXCEPTION( eFileFlush, eFile );
TSS_FILE_EXCEPTION( eFileRewind, eFile );
TSS_FILE_EXCEPTION( eFile, eFileError );
TSS_FILE_EXCEPTION( eFileOpen, eFile );
TSS_FILE_EXCEPTION( eFileWrite, eFile );
TSS_FILE_EXCEPTION( eFileRead, eFile );
TSS_FILE_EXCEPTION( eFileEOF, eFile ); // never used!
TSS_FILE_EXCEPTION( eFileSeek, eFile );
TSS_FILE_EXCEPTION( eFileInvalidOp, eFile ); // never used!
TSS_FILE_EXCEPTION( eFileTrunc, eFile );
TSS_FILE_EXCEPTION( eFileClose, eFile ); // never used!
TSS_FILE_EXCEPTION( eFileFlush, eFile );
TSS_FILE_EXCEPTION( eFileRewind, eFile );
//=============================================================================
// cFile
@ -81,64 +81,64 @@ public:
#endif // IS_UNIX
enum SeekFrom
{
enum SeekFrom
{
SEEK_BEGIN = 0,
SEEK_CURRENT,
SEEK_EOF
};
};
enum OpenFlags
{
// note that reading from the file is implicit
OPEN_READ = 0x00000001, // not needed, but makes calls nice...
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_TRUNCATE = 0x00000008, // opens an empty file. creates it if it doesn't exist. Doesn't make much sense without OF_WRITE
OPEN_CREATE = 0x00000010, // create the file if it doesn't exist; this is implicit if OF_TRUNCATE is set
enum OpenFlags
{
// note that reading from the file is implicit
OPEN_READ = 0x00000001, // not needed, but makes calls nice...
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_TRUNCATE = 0x00000008, // opens an empty file. creates it if it doesn't exist. Doesn't make much sense without OF_WRITE
OPEN_CREATE = 0x00000010, // create the file if it doesn't exist; this is implicit if OF_TRUNCATE is set
OPEN_TEXT = 0x00000020,
OPEN_EXCLUSIVE = 0x00000040, // Use O_CREAT | O_EXCL
OPEN_EXCLUSIVE = 0x00000040, // Use O_CREAT | O_EXCL
OPEN_NONBLOCKING = 0x00000080, // Use non-blocking i/o [Unix]
};
};
//Ctor, Dtor, CpyCtor, Operator=:
cFile ( void );
~cFile ( void );
//Ctor, Dtor, CpyCtor, Operator=:
cFile ( void );
~cFile ( void );
/************ User Interface **************************/
/************ User Interface **************************/
// Both Open methods ALWAYS open files in BINARY mode!
void Open ( const TSTRING& sFileName, uint32 flags = OPEN_READ ); //throw(eFile)
void Close ( void ); //throw(eFile)
bool IsOpen ( void ) const;
// Both Open methods ALWAYS open files in BINARY mode!
void Open ( const TSTRING& sFileName, uint32 flags = OPEN_READ ); //throw(eFile)
void Close ( void ); //throw(eFile)
bool IsOpen ( void ) const;
File_t Seek ( File_t offset, SeekFrom From ) const; //throw(eFile)
// Seek returns the current offset after completion
File_t Read ( void* buffer, File_t nBytes ) const; //throw(eFile)
// 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.
File_t Seek ( File_t offset, SeekFrom From ) const; //throw(eFile)
// Seek returns the current offset after completion
File_t Read ( void* buffer, File_t nBytes ) const; //throw(eFile)
// 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.
// 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)
// Write returns the number of bytes that are actually written.
File_t Tell ( void ) const;
// Tell returns the current offset.
bool Flush ( void ); //throw(eFile)
// Flush returns 0 if the currently defined stream is successfully flushed.
void Rewind ( void ) const; //throw(eFile)
// Sets the offset to 0.
File_t GetSize ( void ) const;
// Returns the size of the current file in bytes. Returns -1 if no file is defined.
void Truncate ( File_t offset ); // throw(eFile)
File_t Write ( const void* buffer, File_t nBytes ); //throw(eFile)
// Write returns the number of bytes that are actually written.
File_t Tell ( void ) const;
// Tell returns the current offset.
bool Flush ( void ); //throw(eFile)
// Flush returns 0 if the currently defined stream is successfully flushed.
void Rewind ( void ) const; //throw(eFile)
// Sets the offset to 0.
File_t GetSize ( void ) const;
// Returns the size of the current file in bytes. Returns -1 if no file is defined.
void Truncate ( File_t offset ); // throw(eFile)
private:
cFile ( const cFile& rhs ); //not impl.
cFile& operator= ( const cFile& rhs); //not impl.
cFile ( const cFile& rhs ); //not impl.
cFile& operator= ( const cFile& rhs); //not impl.
//Pointer to the insulated implementation
cFile_i* mpData;
//Pointer to the insulated implementation
cFile_i* mpData;
public:
bool isWritable;
bool isWritable;
};
@ -146,8 +146,8 @@ public:
class cArosPath
{
public:
static TSTRING AsPosix(const TSTRING& in);
static TSTRING AsNative(const TSTRING& in);
static TSTRING AsPosix(const TSTRING& in);
static TSTRING AsNative(const TSTRING& in);
};
#endif

326
src/core/file_unix.cpp Executable file → Normal file
View File

@ -56,14 +56,14 @@
///////////////////////////////////////////////////////////////////////////////
/*static TSTRING util_GetErrnoString()
{
TSTRING ret;
char* pErrorStr = strerror(errno);
TSTRING ret;
char* pErrorStr = strerror(errno);
#ifdef _UNICODE
#error We dont currently support unicode on unix
#error We dont currently support unicode on unix
#else
ret = pErrorStr;
ret = pErrorStr;
#endif
return ret;
return ret;
}*/
///////////////////////////////////////////////////////////////////////////
@ -73,26 +73,26 @@
///////////////////////////////////////////////////////////////////////////
struct cFile_i
{
cFile_i();
~cFile_i();
cFile_i();
~cFile_i();
FILE* mpCurrStream; //currently defined file stream
TSTRING mFileName; //the name of the file we are currently referencing.
FILE* mpCurrStream; //currently defined file stream
TSTRING mFileName; //the name of the file we are currently referencing.
};
//Ctor
cFile_i::cFile_i() :
mpCurrStream(NULL)
mpCurrStream(NULL)
{}
//Dtor
cFile_i::~cFile_i()
{
if (mpCurrStream != NULL)
fclose( mpCurrStream );
mpCurrStream = NULL;
if (mpCurrStream != NULL)
fclose( mpCurrStream );
mpCurrStream = NULL;
mFileName.empty();
mFileName.empty();
}
///////////////////////////////////////////////////////////////////////////
@ -102,18 +102,18 @@ cFile_i::~cFile_i()
///////////////////////////////////////////////////////////////////////////
cFile::cFile() :
mpData(NULL), isWritable(false)
mpData(NULL), isWritable(false)
{
mpData = new cFile_i;
mpData = new cFile_i;
}
cFile::~cFile()
{
if( mpData != NULL)
{
delete mpData;
mpData = NULL;
}
if( mpData != NULL)
{
delete mpData;
mpData = NULL;
}
}
///////////////////////////////////////////////////////////////////////////////
@ -126,44 +126,44 @@ void cFile::Open( const TSTRING& sFileName, uint32 flags )
#else
void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
{
TSTRING sFileName = cArosPath::AsNative(sFileNameC);
TSTRING sFileName = cArosPath::AsNative(sFileNameC);
#endif
mode_t openmode = 0664;
if ( mpData->mpCurrStream != NULL )
Close();
//
// set up the sopen permissions
//
int perm = 0;
mode_t openmode = 0664;
if ( mpData->mpCurrStream != NULL )
Close();
//
// set up the sopen permissions
//
int perm = 0;
TSTRING mode;
TSTRING mode;
if( flags & OPEN_WRITE )
{
perm |= O_RDWR;
isWritable = true;
mode = _T("rb");
if( flags & OPEN_TRUNCATE )
{
perm |= O_TRUNC;
perm |= O_CREAT;
mode = _T("w+b");
}
else
mode = _T("r+b");
}
else
{
perm |= O_RDONLY;
isWritable = false;
mode = _T("rb");
}
if( flags & OPEN_WRITE )
{
perm |= O_RDWR;
isWritable = true;
mode = _T("rb");
if( flags & OPEN_TRUNCATE )
{
perm |= O_TRUNC;
perm |= O_CREAT;
mode = _T("w+b");
}
else
mode = _T("r+b");
}
else
{
perm |= O_RDONLY;
isWritable = false;
mode = _T("rb");
}
if ( flags & OPEN_EXCLUSIVE ) {
perm |= O_CREAT | O_EXCL;
openmode = (mode_t) 0600; // Make sure only root can read the file
}
if ( flags & OPEN_EXCLUSIVE ) {
perm |= O_CREAT | O_EXCL;
openmode = (mode_t) 0600; // Make sure only root can read the file
}
if ( flags & OPEN_CREATE )
perm |= O_CREAT;
@ -172,83 +172,83 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
if( flags & OPEN_NONBLOCKING )
perm |= O_NONBLOCK;
#endif
//
// actually open the file
//
int fh = _topen( sFileName.c_str(), perm, openmode );
if( fh == -1 )
{
throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) );
}
//
// actually open the file
//
int fh = _topen( sFileName.c_str(), perm, openmode );
if( fh == -1 )
{
throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) );
}
#ifndef __AROS__
if( flags & OPEN_LOCKED_TEMP )
{
// unlink this file
if( flags & OPEN_LOCKED_TEMP )
{
// unlink this file
if( 0 != unlink( sFileName.c_str() ) )
{
// we weren't able to unlink file, so close handle and fail
close( fh );
throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) );
}
}
}
#endif
//
// turn the file handle into a FILE*
//
mpData->mpCurrStream = _tfdopen(fh, mode.c_str());
//
// turn the file handle into a FILE*
//
mpData->mpCurrStream = _tfdopen(fh, mode.c_str());
mpData->mFileName = sFileName; //Set mFileName to the newly opened file.
cFile::Rewind();
mpData->mFileName = sFileName; //Set mFileName to the newly opened file.
cFile::Rewind();
}
///////////////////////////////////////////////////////////////////////////
// Close -- Closes mpCurrStream and sets the pointer to NULL
///////////////////////////////////////////////////////////////////////////
void cFile::Close() //throw(eFile)
void cFile::Close() //throw(eFile)
{
if(mpData->mpCurrStream != NULL)
{
fclose( mpData->mpCurrStream );
mpData->mpCurrStream = NULL;
}
mpData->mFileName.empty();
if(mpData->mpCurrStream != NULL)
{
fclose( mpData->mpCurrStream );
mpData->mpCurrStream = NULL;
}
mpData->mFileName.empty();
}
bool cFile::IsOpen( void ) const
{
return( mpData->mpCurrStream != NULL );
return( mpData->mpCurrStream != NULL );
}
///////////////////////////////////////////////////////////////////////////
// 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)
{
//Check to see if a file as been opened yet...
ASSERT( mpData->mpCurrStream != 0);
//Check to see if a file as been opened yet...
ASSERT( mpData->mpCurrStream != 0);
int apiFrom;
switch( From )
{
case cFile::SEEK_BEGIN:
switch( From )
{
case cFile::SEEK_BEGIN:
apiFrom = SEEK_SET;
break;
case cFile::SEEK_CURRENT:
break;
case cFile::SEEK_CURRENT:
apiFrom = SEEK_CUR;
break;
case cFile::SEEK_EOF:
break;
case cFile::SEEK_EOF:
apiFrom = SEEK_END;
break;
default:
//An invalid SeekFrom parameter was passed.
throw( eInternal( _T("file_unix") ) );
}
break;
default:
//An invalid SeekFrom parameter was passed.
throw( eInternal( _T("file_unix") ) );
}
// this is a hack to simulate running out of disk space
#if 0
@ -276,98 +276,98 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile)
///////////////////////////////////////////////////////////////////////////
// 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)
{
File_t iBytesRead;
File_t iBytesRead;
// Has a file been opened?
ASSERT( mpData->mpCurrStream != NULL );
// Has a file been opened?
ASSERT( mpData->mpCurrStream != NULL );
// Is the nBytes parameter 0? If so, return without touching buffer:
if( nBytes == 0 )
return 0;
// Is the nBytes parameter 0? If so, return without touching buffer:
if( nBytes == 0 )
return 0;
iBytesRead = fread( buffer, sizeof(byte), nBytes, mpData->mpCurrStream );
if( ferror( mpData->mpCurrStream ) != 0 )
throw eFileRead( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ;
else
return iBytesRead;
iBytesRead = fread( buffer, sizeof(byte), nBytes, mpData->mpCurrStream );
if( ferror( mpData->mpCurrStream ) != 0 )
throw eFileRead( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ;
else
return iBytesRead;
}
///////////////////////////////////////////////////////////////////////////
// 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?
ASSERT( mpData->mpCurrStream != NULL );
ASSERT( isWritable );
// Has a file been opened? Is it writable?
ASSERT( mpData->mpCurrStream != NULL );
ASSERT( isWritable );
if( ( actual_count = fwrite( buffer, sizeof(byte), nBytes, mpData->mpCurrStream ) ) < nBytes )
throw eFileWrite( mpData->mFileName, iFSServices::GetInstance()->GetErrString() );
else
return actual_count;
if( ( actual_count = fwrite( buffer, sizeof(byte), nBytes, mpData->mpCurrStream ) ) < nBytes )
throw eFileWrite( mpData->mFileName, iFSServices::GetInstance()->GetErrString() );
else
return actual_count;
}
///////////////////////////////////////////////////////////////////////////
// Tell -- Returns the current file offset. Returns 0 if no file has been
// opened.
// opened.
///////////////////////////////////////////////////////////////////////////
cFile::File_t cFile::Tell() const
{
ASSERT( mpData->mpCurrStream != 0);
ASSERT( mpData->mpCurrStream != 0);
return ftell( mpData->mpCurrStream );
return ftell( mpData->mpCurrStream );
}
///////////////////////////////////////////////////////////////////////////
// Flush -- Flushes the current stream.
///////////////////////////////////////////////////////////////////////////
bool cFile::Flush() //throw(eFile)
bool cFile::Flush() //throw(eFile)
{
if ( mpData->mpCurrStream == NULL )
throw eFileFlush( mpData->mFileName, iFSServices::GetInstance()->GetErrString() );
return ( fflush( mpData->mpCurrStream) == 0 );
if ( mpData->mpCurrStream == NULL )
throw eFileFlush( mpData->mFileName, iFSServices::GetInstance()->GetErrString() );
return ( fflush( mpData->mpCurrStream) == 0 );
}
///////////////////////////////////////////////////////////////////////////
// Rewind -- Sets the offset to the beginning of the file. If mpCurrStream
// is NULL, this method returns false. If the rewind operation fails,
// an exception is thrown.
// is NULL, this method returns false. If the rewind operation fails,
// 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 );
if( ftell( mpData->mpCurrStream ) != 0 )
throw( eFileRewind( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) );
rewind( mpData->mpCurrStream );
if( ftell( mpData->mpCurrStream ) != 0 )
throw( eFileRewind( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) );
}
///////////////////////////////////////////////////////////////////////////
// GetSize -- Returns the size of the current stream, if one has been
// opened. If no stream has been opened, returns -1.
// opened. If no stream has been opened, returns -1.
///////////////////////////////////////////////////////////////////////////
cFile::File_t cFile::GetSize() const
{
File_t vCurrentOffset = Tell(); //for saving the current offset
File_t ret;
File_t vCurrentOffset = Tell(); //for saving the current offset
File_t ret;
//Has a file been opened? If not, return -1
if( mpData->mpCurrStream == NULL )
return -1;
//Has a file been opened? If not, return -1
if( mpData->mpCurrStream == NULL )
return -1;
ret = Seek( 0, cFile::SEEK_EOF );
Seek( vCurrentOffset, cFile::SEEK_BEGIN );
//return the offset to it's position prior to GetSize call.
ret = Seek( 0, cFile::SEEK_EOF );
Seek( vCurrentOffset, cFile::SEEK_BEGIN );
//return the offset to it's position prior to GetSize call.
return ret;
return ret;
}
/////////////////////////////////////////////////////////////////////////
@ -375,39 +375,39 @@ cFile::File_t cFile::GetSize() const
/////////////////////////////////////////////////////////////////////////
void cFile::Truncate( File_t offset ) // throw(eFile)
{
ASSERT( mpData->mpCurrStream != 0);
ASSERT( isWritable );
ASSERT( mpData->mpCurrStream != 0);
ASSERT( isWritable );
ftruncate( fileno(mpData->mpCurrStream), offset );
if( GetSize() != offset )
throw( eFileTrunc( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) );
ftruncate( fileno(mpData->mpCurrStream), offset );
if( GetSize() != offset )
throw( eFileTrunc( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) );
}
#ifdef __AROS__
TSTRING cArosPath::AsPosix( const TSTRING& in )
{
if (in[0] == '/')
return in;
if (in[0] == '/')
return in;
TSTRING out = '/' + in;
std::replace(out.begin(), out.end(), ':', '/');
TSTRING out = '/' + in;
std::replace(out.begin(), out.end(), ':', '/');
return out;
return out;
}
TSTRING cArosPath::AsNative( const TSTRING& in )
{
if (in[0] != '/')
return in;
if (in[0] != '/')
return in;
int x;
for (x=1; in[x] == '/' && x<in.length(); x++);
int x;
for (x=1; in[x] == '/' && x<in.length(); x++);
TSTRING out = in.substr(x);
TSTRING::size_type t = out.find_first_of('/');
out[t] = ':';
TSTRING out = in.substr(x);
TSTRING::size_type t = out.find_first_of('/');
out[t] = ':';
return out;
return out;
}
#endif

View File

@ -40,37 +40,37 @@
eFileError::eFileError( const TSTRING& filename, const TSTRING& description, uint32 flags )
: eError( _T(""), flags )
{
mFilename = filename;
mMsg = description;
mFilename = filename;
mMsg = description;
}
TSTRING eFileError::GetFilename() const
{
return mFilename;
return mFilename;
}
TSTRING eFileError::GetDescription() const
{
return mMsg;
return mMsg;
}
/* virtual */ TSTRING eFileError::GetMsg() const
{
TSTRING ret;
TSTRING ret;
if( ! mFilename.empty() )
{
if( ! mFilename.empty() )
{
ret = TSS_GetString( cCore, core::STR_ERROR_FILENAME ) + mFilename;
}
}
if( ! mMsg.empty() )
{
if ( ! mFilename.empty() )
ret += _T("\n");
{
if ( ! mFilename.empty() )
ret += _T("\n");
ret += mMsg;
}
}
return ret;
return ret;
}

View File

@ -53,28 +53,28 @@
//=============================================================================
TSS_BEGIN_EXCEPTION_NO_CTOR( eFileError, eError )
private:
TSTRING mFilename;
TSTRING mFilename;
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 )
: eError( rhs ) { mFilename = rhs.mFilename; }
eFileError( const TSTRING& msg, uint32 flags = 0 )
: eError( msg, flags ) {}
explicit eFileError( const eFileError& rhs )
: eError( rhs ) { mFilename = rhs.mFilename; }
eFileError( const TSTRING& msg, uint32 flags = 0 )
: eError( msg, flags ) {}
TSTRING GetFilename() const;
TSTRING GetDescription() const;
virtual TSTRING GetMsg() const;
TSTRING GetFilename() const;
TSTRING GetDescription() const;
virtual TSTRING GetMsg() const;
TSS_END_EXCEPTION()
#define TSS_FILE_EXCEPTION( except, base ) \
TSS_BEGIN_EXCEPTION( except, base ) \
except( const TSTRING& filename, const TSTRING& msg, uint32 flags = 0 ) \
: base( filename, msg, flags ) {} \
TSS_END_EXCEPTION()
TSS_BEGIN_EXCEPTION( except, base ) \
except( const TSTRING& filename, const TSTRING& msg, uint32 flags = 0 ) \
: base( filename, msg, flags ) {} \
TSS_END_EXCEPTION()
#endif

14
src/core/fileheader.cpp Executable file → Normal file
View File

@ -110,17 +110,17 @@ int cFileHeaderID::operator==( const cFileHeaderID& rhs ) const
( ::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;
pSerializer->ReadInt16( len );
if ( (len < 0) || (len >= cFileHeaderID::MAXBYTES ))
{
// this is invalid!
throw eSerializerInputStreamFmt( _T("File Header ID invalid") );
}
if ( (len < 0) || (len >= cFileHeaderID::MAXBYTES ))
{
// this is invalid!
throw eSerializerInputStreamFmt( _T("File Header ID invalid") );
}
pSerializer->ReadBlob(mID, len * sizeof(char));
mIDLen = len;
mIDLen = len;
}
void cFileHeaderID::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive)

8
src/core/fileheader.h Executable file → Normal file
View File

@ -59,8 +59,8 @@ public:
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 Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
private:
// For now we will store the id as a string.
@ -127,8 +127,8 @@ public:
cMemoryArchive& GetBaggage();
const cMemoryArchive& GetBaggage() const;
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
protected:
cFileHeaderID mID;

View File

@ -45,26 +45,26 @@
//-----------------------------------------------------------------------------
// cGrowHeap -- a heap that can grow but never shrink
// All items alloced should be well below growBy in size
// All items alloced should be well below growBy in size
//-----------------------------------------------------------------------------
class cGrowHeap_i;
class cGrowHeap
{
public:
cGrowHeap( size_t initialSize, size_t growby, const TCHAR* name );
// creates a heap that is initially initialSize big, and increases the
// size by growBy every time there is no more room.
cGrowHeap( size_t initialSize, size_t growby, const TCHAR* name );
// creates a heap that is initially initialSize big, and increases the
// size by growBy every time there is no more room.
// initialSize and growby must be a multiple of BYTE_ALIGN
~cGrowHeap();
~cGrowHeap();
void* Malloc( size_t size );
void Clear();
// resets the grow heap's state.
size_t TotalMemUsage() const;
// returns the total memory usage of this heap
void* Malloc( size_t size );
void Clear();
// resets the grow heap's state.
size_t TotalMemUsage() const;
// returns the total memory usage of this heap
private:
cGrowHeap_i* mpData;
cGrowHeap_i* mpData;
};

View File

@ -36,7 +36,7 @@
// operator overloaded in order for this to work. TSTRINGS will always
// work as the key value because of the overloaded-template-function
//
// Note: Any overloaded const byte*() operator must return an
// Note: Any overloaded const byte*() operator must return an
// length of key as well. see cDefaultConvert
//
// IMPORTANT -- cDefaultConvert only works for pointers to objects
@ -63,18 +63,18 @@
///////////////////////////////////////////////////////////////////////////////
// Comparison function objects ... these are used by the hash table to determine
// equality. The one defined should work for objects that use op== to define
// 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
// equality. The one defined should work for objects that use op== to define
// 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
///////////////////////////////////////////////////////////////////////////////
template<class T>
class cDefaultCompare
{
public:
bool operator()(const T& lhs, const T& rhs)
{
return lhs == rhs;
}
bool operator()(const T& lhs, const T& rhs)
{
return lhs == rhs;
}
};
/////////////////////////////////////////////////////////
// specialization for TSTRINGS
@ -82,24 +82,24 @@ public:
template<>
inline bool cDefaultCompare<TSTRING>::operator()(const TSTRING& lhs, const TSTRING& rhs)
{
return (lhs.compare(rhs) == 0);
return (lhs.compare(rhs) == 0);
}
///////////////////////////////////////////////////////////////////////////////
// Conversion function objects ... used by the hash table to locate the key in KEY_TYPE
// into a byte* and a key length (for hashing purposes). The default implementation
// just does a cast. A specialization is also provided for TSTRINGs.
// into a byte* and a key length (for hashing purposes). The default implementation
// just does a cast. A specialization is also provided for TSTRINGs.
///////////////////////////////////////////////////////////////////////////////
template<class T>
class cDefaultConvert
{
public:
const byte* operator()(const T& obj, int* const pcbKeyLen)
{
const byte* operator()(const T& obj, int* const pcbKeyLen)
{
// HACK! TODO: in the interest of time, I've left this as it is.....
*pcbKeyLen = sizeof(TCHAR) * _tcslen(obj);
return (byte*)obj;
}
return (byte*)obj;
}
};
/////////////////////////////////////////////////////////
// specialization for TSTRINGS
@ -108,27 +108,27 @@ template<>
inline const byte* cDefaultConvert<TSTRING>::operator()(const TSTRING& obj, int* const pcbKeyLen )
{
*pcbKeyLen = sizeof(TCHAR) * obj.length();
return (byte*)obj.c_str();
return (byte*)obj.c_str();
}
///////////////////////////////////////////////////////////////////////////////
// cHashTable<KEY, VAL, CMP, CONVERTER>
// KEY -- the key you are hashing on
// VAL -- the value you want associated with that key
// CMP -- a function object that takes (KEY, KEY) and returns true if they
// are equal.
// CONVERTER -- function object that takes (KEY, int* pcbKeyLen) and returns a const byte*
// KEY -- the key you are hashing on
// VAL -- the value you want associated with that key
// CMP -- a function object that takes (KEY, KEY) and returns true if they
// are equal.
// CONVERTER -- function object that takes (KEY, int* pcbKeyLen) and returns a const byte*
// ( points to start of key ) and a byte length (in pcbKeyLen) that tells the hashtable
// how long the key is
///////////////////////////////////////////////////////////////////////////////
// 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
enum cHashTable_TableSize {
HASH_VERY_SMALL = 17,
HASH_SMALL = 2007,
HASH_MEDIUM = 6007,
HASH_LARGE = 13007,
HASH_VERY_LARGE = 49999
HASH_VERY_SMALL = 17,
HASH_SMALL = 2007,
HASH_MEDIUM = 6007,
HASH_LARGE = 13007,
HASH_VERY_LARGE = 49999
};
// forward declaration
@ -141,48 +141,48 @@ class cHashTable
{
friend class cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>;
public:
//structure for hash table nodes.
struct node {
KEY_TYPE nKey;
VAL_TYPE nData;
node* next;
};
//structure for hash table nodes.
struct node {
KEY_TYPE nKey;
VAL_TYPE nData;
node* next;
};
cHashTable(int tblSize = HASH_MEDIUM);
~cHashTable();
cHashTable(int tblSize = HASH_MEDIUM);
~cHashTable();
bool Insert(KEY_TYPE key, VAL_TYPE data_in);
// 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)
// returns true if (key) already existed in table. otherwise, returns false
bool Lookup(KEY_TYPE 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
//to the node in the table that matches string_check is passed back (by ref).
bool Remove(KEY_TYPE key);
//The node that matches string_out is de-allocated.
bool Insert(KEY_TYPE key, VAL_TYPE data_in);
// 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)
// returns true if (key) already existed in table. otherwise, returns false
bool Lookup(KEY_TYPE 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
//to the node in the table that matches string_check is passed back (by ref).
bool Remove(KEY_TYPE key);
//The node that matches string_out is de-allocated.
bool Clear(void);
//Clears the entire table and sets all node pointers to NULL
bool IsEmpty(void) const;
uint32 Hash( const KEY_TYPE& key ) const;
//The hashing function, taken from old Tripwire
bool Clear(void);
//Clears the entire table and sets all node pointers to NULL
bool IsEmpty(void) const;
uint32 Hash( const KEY_TYPE& key ) const;
//The hashing function, taken from old Tripwire
int32 GetNumValues() const { return mValuesInTable; };
// returns number of table entries filled
#ifdef _DEBUG
void TraceDiagnostics() const;
// traces hash table statistics
void TraceDiagnostics() const;
// traces hash table statistics
#endif
private:
cHashTable(const cHashTable& rhs); // not impl
void operator=(const cHashTable& rhs); // not impl
node** mTable;
int mTableSize;
cHashTable(const cHashTable& rhs); // not impl
void operator=(const cHashTable& rhs); // not impl
node** mTable;
int mTableSize;
int32 mValuesInTable;
};
@ -194,23 +194,23 @@ template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
class cHashTableIter
{
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;
bool Done() const;
void Next() const;
void SeekBegin() const;
bool Done() const;
void Next() const;
const KEY_TYPE& Key() const;
const VAL_TYPE& Val() const;
VAL_TYPE& Val();
const KEY_TYPE& Key() const;
const VAL_TYPE& Val() const;
VAL_TYPE& Val();
private:
mutable int mCurIndex;
mutable typename cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::node* mpCurNode;
const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& mHashTable;
mutable int mCurIndex;
mutable typename cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::node* mpCurNode;
const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& mHashTable;
// helper function
void SeekNextValid() const;
// helper function
void SeekNextValid() const;
};
@ -223,61 +223,61 @@ private:
///////////////////////////////////////////////////////////////////////////////
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) :
mHashTable(hashTbl)
mHashTable(hashTbl)
{
SeekBegin();
SeekBegin();
}
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::SeekBegin() const
{
mCurIndex = 0;
mpCurNode = mHashTable.mTable[0];
if(! mpCurNode)
SeekNextValid();
mCurIndex = 0;
mpCurNode = mHashTable.mTable[0];
if(! mpCurNode)
SeekNextValid();
}
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>
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>
inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::SeekNextValid() const
{
if(mpCurNode)
mpCurNode = mpCurNode->next;
//mCurIndex++;
while((! mpCurNode) && (mCurIndex < mHashTable.mTableSize))
{
mpCurNode = mHashTable.mTable[++mCurIndex];
}
if(mpCurNode)
mpCurNode = mpCurNode->next;
//mCurIndex++;
while((! mpCurNode) && (mCurIndex < mHashTable.mTableSize))
{
mpCurNode = mHashTable.mTable[++mCurIndex];
}
}
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());
return mpCurNode->nKey;
ASSERT(! Done());
return mpCurNode->nKey;
}
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());
return mpCurNode->nData;
ASSERT(! Done());
return mpCurNode->nData;
}
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline VAL_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Val()
{
ASSERT(! Done());
return mpCurNode->nData;
ASSERT(! Done());
return mpCurNode->nData;
}
///////////////////////////////////////////////////////////////////////////////
@ -289,98 +289,98 @@ template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::cHashTable(int tblSize)
{
mValuesInTable = 0;
mTableSize = tblSize;
mTable = new node*[mTableSize];
mTableSize = tblSize;
mTable = new node*[mTableSize];
for (int i=0; i < mTableSize; ++i)
mTable[i] = NULL;
for (int i=0; i < mTableSize; ++i)
mTable[i] = NULL;
}
//Destructor steps through table and deallocates all dynamic memory
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::~cHashTable()
{
for (int i=0; i<mTableSize; ++i)
{
if (mTable[i] != NULL)
{
//delete the entire chain:
node* curr = mTable[i];
node* del;
while(curr != NULL)
{
del = curr;
curr=curr->next;
for (int i=0; i<mTableSize; ++i)
{
if (mTable[i] != NULL)
{
//delete the entire chain:
node* curr = mTable[i];
node* del;
while(curr != NULL)
{
del = curr;
curr=curr->next;
delete del;
}
}
}
delete del;
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Insert -- Hashes a const TCHAR* to a new index. Collisions are resolved
// using seperate chaining (link lists).
// using seperate chaining (link lists).
////////////////////////////////////////////////////////////////////////////////
// General Version:
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)
{
COMPARE_OP compare;
COMPARE_OP compare;
int hindex = Hash( key );
if (mTable[hindex] == NULL) {
//open index, perform insert
mTable[hindex] = new node;
(mTable[hindex])->nKey = key;
(mTable[hindex])->next = NULL;
(mTable[hindex])->nData = d_in;
int hindex = Hash( key );
if (mTable[hindex] == NULL) {
//open index, perform insert
mTable[hindex] = new node;
(mTable[hindex])->nKey = key;
(mTable[hindex])->next = NULL;
(mTable[hindex])->nData = d_in;
mValuesInTable++;
return false;
}
else //collision, do linked list insert
{
// case 1: key already exists in list -- replace existing one
// case 2: key does not exist -- add to end of list
node* nodeptr = mTable[hindex];
return false;
}
else //collision, do linked list insert
{
// case 1: key already exists in list -- replace existing one
// case 2: key does not exist -- add to end of list
node* nodeptr = mTable[hindex];
bool found = false;
while (true)
{
if ( compare(nodeptr->nKey, key))
{
// we found a duplicate!
found = true;
break;
}
bool found = false;
while (true)
{
if ( compare(nodeptr->nKey, key))
{
// we found a duplicate!
found = true;
break;
}
// break if this is the last node in the list
if(! nodeptr->next)
break;
// break if this is the last node in the list
if(! nodeptr->next)
break;
// otherwise, keep traversing
nodeptr = nodeptr->next;
}
// add a node if the key was not found
if (! found)
{
node *prev = nodeptr;
nodeptr = new node;
nodeptr->nKey = key;
nodeptr->next = NULL;
prev->next = nodeptr;
// otherwise, keep traversing
nodeptr = nodeptr->next;
}
// add a node if the key was not found
if (! found)
{
node *prev = nodeptr;
nodeptr = new node;
nodeptr->nKey = key;
nodeptr->next = NULL;
prev->next = nodeptr;
mValuesInTable++;
}
mValuesInTable++;
}
// whether it is a new node or not, set the data to this new value
nodeptr->nData = d_in;
// whether it is a new node or not, set the data to this new value
nodeptr->nData = d_in;
return found;
}
return found;
}
}
////////////////////////////////////////////////////////////////////////////////
@ -391,60 +391,60 @@ template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool
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 );
if (mTable[hindex] == NULL)
return false;
else {
node* nodeptr = mTable[hindex];
while (nodeptr != NULL)
{
if( compare(nodeptr->nKey, key)) {
d_out = nodeptr->nData;
return true;
}
nodeptr = nodeptr->next;
}
}
return false; //mTable entries exhausted without a match
int hindex = Hash( key );
if (mTable[hindex] == NULL)
return false;
else {
node* nodeptr = mTable[hindex];
while (nodeptr != NULL)
{
if( compare(nodeptr->nKey, key)) {
d_out = nodeptr->nData;
return true;
}
nodeptr = nodeptr->next;
}
}
return false; //mTable entries exhausted without a match
}
////////////////////////////////////////////////////////////////////////////////
// Remove -- Removes a single entry from the hash table. Returns false if
// the nKey is not found in the table.
// the nKey is not found in the table.
////////////////////////////////////////////////////////////////////////////////
// General Version -
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Remove(KEY_TYPE key)
{
COMPARE_OP compare;
COMPARE_OP compare;
int hindex = Hash( key );
if (mTable[hindex] == NULL) {
delete (mTable[hindex]);
mTable[hindex] = NULL;
return true;
}
else {
node* nodeptr = mTable[hindex];
node* prev;
while(nodeptr != NULL) {
prev = nodeptr;
if(compare(mTable[hindex]->nKey, key))
{
prev->next = nodeptr->next;
delete nodeptr;
if (nodeptr == mTable[hindex])
mTable[hindex] = NULL;
nodeptr = NULL;
return true;
}//end if
nodeptr = nodeptr->next;
}//end while
}//end else
return false; //match was not found, no node deleted
int hindex = Hash( key );
if (mTable[hindex] == NULL) {
delete (mTable[hindex]);
mTable[hindex] = NULL;
return true;
}
else {
node* nodeptr = mTable[hindex];
node* prev;
while(nodeptr != NULL) {
prev = nodeptr;
if(compare(mTable[hindex]->nKey, key))
{
prev->next = nodeptr->next;
delete nodeptr;
if (nodeptr == mTable[hindex])
mTable[hindex] = NULL;
nodeptr = NULL;
return true;
}//end if
nodeptr = nodeptr->next;
}//end while
}//end else
return false; //match was not found, no node deleted
}
////////////////////////////////////////////////////////////////////////////////
@ -454,23 +454,23 @@ template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Clear(void)
{
for (int i=0; i<mTableSize; ++i)
{
if (mTable[i] != NULL) {
node* curr = mTable[i];
node* del;
while(curr != NULL) {
del = curr;
curr=curr->next;
delete del;
if (del == mTable[i])
mTable[i] = NULL;
del = NULL;
}//end delete chain loop
}//end if mTable[i]!= NULL
}//end for
return (IsEmpty());
for (int i=0; i<mTableSize; ++i)
{
if (mTable[i] != NULL) {
node* curr = mTable[i];
node* del;
while(curr != NULL) {
del = curr;
curr=curr->next;
delete del;
if (del == mTable[i])
mTable[i] = NULL;
del = NULL;
}//end delete chain loop
}//end if mTable[i]!= NULL
}//end for
return (IsEmpty());
}
////////////////////////////////////////////////////////////////////////////////
@ -480,10 +480,10 @@ template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::IsEmpty(void) const
{
bool ret = true;
for(int i=0; i< mTableSize; ++i)
ret &= (mTable[i] == NULL);
return ret;
bool ret = true;
for(int i=0; i< mTableSize; ++i)
ret &= (mTable[i] == NULL);
return ret;
}
////////////////////////////////////////////////////////////////////////////////
@ -495,10 +495,10 @@ uint32 cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Hash( const KEY_TY
CONVERTER converter;
int len;
const byte* pb = converter( key, &len ); //locates key
uint32 hindex;
uint32 hindex;
hindex = *pb;
while (len-- > 0)
while (len-- > 0)
hindex = ((hindex << 9) ^ *pb++) % mTableSize;
return hindex;
}
@ -508,34 +508,34 @@ uint32 cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Hash( const KEY_TY
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
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;
node* pNode;
int slotsFilled = 0, numItems = 0, numMultiSlot = 0;
node* pNode;
for(int i=0; i < mTableSize; i++)
{
if(mTable[i] != NULL)
{
slotsFilled++;
numItems++;
pNode = (mTable[i])->next;
if(pNode != NULL)
numMultiSlot++;
while(pNode)
{
numItems++;
pNode = pNode->next;
}
}
}
for(int i=0; i < mTableSize; i++)
{
if(mTable[i] != NULL)
{
slotsFilled++;
numItems++;
pNode = (mTable[i])->next;
if(pNode != NULL)
numMultiSlot++;
while(pNode)
{
numItems++;
pNode = pNode->next;
}
}
}
d.TraceDebug("---------------Hash Table Statisics---------------\n");
d.TraceDebug("-- Number of slots: %d\n", mTableSize);
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 with >1 item: %d (%lf %%)\n",numMultiSlot, ((double)numMultiSlot / (double)slotsFilled) * 100.0);
d.TraceDebug("--------------------------------------------------\n");
d.TraceDebug("---------------Hash Table Statisics---------------\n");
d.TraceDebug("-- Number of slots: %d\n", mTableSize);
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 with >1 item: %d (%lf %%)\n",numMultiSlot, ((double)numMultiSlot / (double)slotsFilled) * 100.0);
d.TraceDebug("--------------------------------------------------\n");
}
#endif // _DEBUG

View File

@ -1,220 +0,0 @@
//
// The developer of the original code and/or files is Tripwire, Inc.
// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire,
// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights
// reserved.
//
// This program is free software. The contents of this file are subject
// to the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. You may redistribute it and/or modify it
// only in compliance with the GNU General Public License.
//
// This program is distributed in the hope that it will be useful.
// However, this program is distributed AS-IS WITHOUT ANY
// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// Nothing in the GNU General Public License or any other license to use
// the code or files shall permit you to use Tripwire's trademarks,
// service marks, or other intellectual property without Tripwire's
// prior written consent.
//
// If you have any questions, please contact Tripwire, Inc. at either
// info@tripwire.org or www.tripwire.org.
//
//hashtable_t.cpp : Test suite for cHashTable.
#include "stdcore.h"
#include "hashtable.h"
#include <iostream>
#ifndef __TEST_H
#include "test/test.h"
#endif
//#include "dummy.h"
using namespace std;
void HashTest1();
void HashTest2();
void TestHashTable(void)
{
HashTest1();
HashTest2();
}
void HashTest1()
{
//Test the Hash table with Key = TSTRING
cHashTable<TSTRING, void*> htable;
cDebug d("TestHashTable()::Test1");
d.TraceDetail("Entering ...\n");
//return val for all function calls.
bool ret = true;
//test data
TSTRING string = _T("test string");
TSTRING string2 = _T("another test string");
TSTRING string3 = _T("yet another test string");
void* data_ptr = NULL;
void* data_ptr2 = NULL;
void* data_ptr3 = NULL;
void* test_lookup = NULL;
int var = 32;
int var2 = 33;
int* test = &var;
int* test2 = &var2;
data_ptr = test;
data_ptr2 = test2;
//Test insert and lookup.
htable.Insert(string, data_ptr);
ret &= htable.Lookup(string, test_lookup);
TEST(ret);
//Make sure value is being stored and returned correctly
d.TraceDetail("Value returned from table is %i, and should be %i.\n", *((int*)test_lookup), var);
TEST(*((int*)test_lookup) == var);
//Check remove and lookup (lookup should fail)
ret &= htable.Remove(string);
TEST(ret);
ret &= !htable.Lookup(string, test_lookup);
TEST(ret);
//Has test_lookup's value changed? It shouldn't have...
TEST(*((int*)test_lookup) == var);
//Insert and Remove different string/key combo.
htable.Insert(string2, data_ptr2);
htable.Insert(string3, data_ptr3);
// test iteration
cHashTableIter<TSTRING, void*> iter(htable);
d.TraceDebug("Testing the iterator:\n");
for(iter.SeekBegin(); ! iter.Done(); iter.Next())
{
d.TraceDebug(_T("Key=%s\tValue=%d\n"), iter.Key().c_str(), iter.Val());
}
// get statistics
#ifdef _DEBUG
htable.TraceDiagnostics();
#endif
//Test IsEmpty()
ret &= !htable.IsEmpty();
TEST(!htable.IsEmpty());
//Test Clear(), IsEmpty()
ret &= htable.Clear();
TEST(htable.Clear());
ret &= htable.IsEmpty();
TEST(htable.IsEmpty());
/*
//Test the Hash table with arbitrary key
//Won't work with int!! (oops). I'll need to make one of our data types
// const TCHAR*() capable. Casting an int to a TCHAR* just returns an address,
// so there's no way to properly hash (no length, etc).
cHashTable<cDummy, void*> htable2;
cDummy key1, key2;
key1.SetInt(40);
key2.SetInt(50);
test_lookup = NULL;
//Test insert and lookup.
htable2.Insert(key1, data_ptr);
TEST(ret &= htable2.Lookup(key1, test_lookup));
//Make sure value is being stored and returned correctly
d.TraceDetail("Value returned from table is %i, and should be %i.\n", *((int*)test_lookup), var);
TEST(*((int*)test_lookup) == var);
//Check remove and lookup (lookup should fail)
TEST(ret &= htable2.Remove(key1));
TEST(ret &= !htable2.Lookup(key1, test_lookup));
//Has test_lookup's value changed? It shouldn't have...
TEST(*((int*)test_lookup) == var);
//Insert and different key/val combo.
htable2.Insert(key2, data_ptr2);
//Test IsEmpty()
ret &= !htable2.IsEmpty();
TEST(!htable2.IsEmpty());
//Test Clear(), IsEmpty()
ret &= htable2.Clear();
TEST(htable2.Clear());
ret &= htable2.IsEmpty();
TEST(htable2.IsEmpty());
*/
return;
}
void HashTest2()
{
cDebug d("TestHashTable()::Test2");
d.TraceDebug("entering...\n");
{
cHashTable <TSTRING, TSTRING> tbl;
// test insert and lookup
TEST(tbl.Insert(_T("foo"), _T("foo")) == false);
TSTRING val;
TEST(tbl.Lookup(_T("foo"), val));
TEST(val.compare(_T("foo")) == 0);
// check Empty() on non-empty list
TEST(tbl.IsEmpty() == false);
// test insertion with collision
TEST(tbl.Insert(_T("foo"), _T("bar")) == true);
TEST(tbl.Lookup(_T("foo"), val));
TEST(val.compare(_T("bar")) == 0);
// test removal
TEST(tbl.Remove(_T("foo")));
// make sure it's totally empty (confirms that hash table insertion worked!)
TEST(tbl.IsEmpty());
// test another insertion
TEST(tbl.Insert(_T("a"), _T("bcd")) == false);
TEST(tbl.Insert(_T("b"), _T("def")) == false);
TSTRING v1, v2;
TEST(tbl.Lookup(_T("a"), v1));
TEST(tbl.Lookup(_T("b"), v2));
TEST(v1.compare(_T("bcd")) == 0);
TEST(v2.compare(_T("def")) == 0);
// remove and test IsEmpty()
TEST(tbl.Remove(_T("a")));
TEST(tbl.IsEmpty() == false);
TEST(tbl.Remove(_T("b")));
TEST(tbl.IsEmpty() == true);
}
d.TraceDebug("PASSED!\n");
}

View File

@ -71,11 +71,14 @@
/*
* Some comments on getting Haval into Tripwire:
*
* - all #elif directives replaced by ugly #if/#else/#endif sequences.
* not all compilers support #elif (an ANSI construct).
* - byte-order is discovered at compile time. we use the information
* in "../../include/byteorder.h" to get this information.
* - all #elif directives replaced by ugly #if/#else/#endif sequences.
* not all compilers support #elif (an ANSI construct).
* - byte-order is discovered at compile time. we use the information
* in "../../include/byteorder.h" to get this information.
*/
#pragma GCC diagnostic ignored "-Wparentheses"
#include "stdcore.h"
#include "config.h"
#include <stdio.h>
@ -87,7 +90,7 @@
#include "haval.h"
#include "debug.h"
#define HAVAL_VERSION 1 /* current version number */
#define HAVAL_VERSION 1 /* current version number */
/* Do not remove this line. Protyping depends on it! */
#if defined(__STDC__) || defined(__cplusplus)

File diff suppressed because it is too large Load Diff

View File

@ -56,21 +56,21 @@
*/
#ifdef __STDC__
void le_clobber(void);
int le_set(char *);
int le_unset(char *);
int le_set(const char*);
int le_unset(const char*);
int le_umask(int);
int le_openfd(int);
int le_closefd(int);
int le_euid(int);
int le_egid(int);
int msystem(char *);
FILE *mpopen(char *, char *);
int msystem(const char*);
FILE *mpopen(const char*, const char*);
int mpclose(FILE *);
int mfpopen(char *, FILE *[]);
int mfpopen(const char*, FILE *[]);
int mfpclose(int, FILE *[]);
int mxfpopen(char *[], FILE *[]);
int mxfpopen(const char*[], FILE *[]);
int mxfpclose(int, FILE *[]);
int schild(char *, char *[], char *[], FILE *[], int);
int schild(const char*, const char*[], const char*[], FILE *[], int);
int echild(int);
#else
void le_clobber();
@ -95,41 +95,41 @@ int echild();
/*
* define error codes
*/
#define SE_NONE 0 /* no error */
#define SE_NOMEM -1 /* no memory */
#define SE_NOPIPE -2 /* no pipes */
#define SE_NOVAR -3 /* variable not defined */
#define SE_BADFD -4 /* invalid file descriptor */
#define SE_NONE 0 /* no error */
#define SE_NOMEM -1 /* no memory */
#define SE_NOPIPE -2 /* no pipes */
#define SE_NOVAR -3 /* variable not defined */
#define SE_BADFD -4 /* invalid file descriptor */
/*
* default security settings
*/
#ifndef DEF_UMASK
# define DEF_UMASK 077 /* only owner has privileges */
# define DEF_UMASK 077 /* only owner has privileges */
#endif
#ifndef UID_RESET
# define UID_RESET -2 /* reset EUID to RUID */
# define UID_RESET -2 /* reset EUID to RUID */
#endif
#ifndef GID_RESET
# define GID_RESET -2 /* reset EGID to RGID */
# define GID_RESET -2 /* reset EGID to RGID */
#endif
#ifndef DEF_PATH
# ifdef __FreeBSD_cc_version
# define DEF_PATH "PATH=/sbin:/usr/sbin:/bin:/usr/bin" /* default search path */
# else
# define DEF_PATH "PATH=/bin:/usr/bin:/usr/ucb" /* default search path */
# endif
# ifdef __FreeBSD_cc_version
# define DEF_PATH "PATH=/sbin:/usr/sbin:/bin:/usr/bin" /* default search path */
# else
# define DEF_PATH "PATH=/bin:/usr/bin:/usr/ucb" /* default search path */
# endif
#endif
#ifndef DEF_SHELL
# define DEF_SHELL "SHELL=/bin/sh" /* default shell */
# define DEF_SHELL "SHELL=/bin/sh" /* default shell */
#endif
#ifndef DEF_IFS
# define DEF_IFS "IFS= \t\n" /* default IFS */
# define DEF_IFS "IFS= \t\n" /* default IFS */
#endif
#ifndef DEF_TZ
# define DEF_TZ "TZ" /* default TZ */
# define DEF_TZ "TZ" /* default TZ */
#endif
#ifndef NOSHELL
# define NOSHELL "/bin/sh" /* use this if no shell */
# define NOSHELL "/bin/sh" /* use this if no shell */
#endif

View File

@ -40,10 +40,10 @@
class cBlockLink
{
public:
cBlockLink(cBlockLink* pNext) : mpNext(pNext) {}
cBlockLink* Next() { return mpNext; }
cBlockLink(cBlockLink* pNext) : mpNext(pNext) {}
cBlockLink* Next() { return mpNext; }
private:
cBlockLink* mpNext; // pointer to the next link, or NULL
cBlockLink* mpNext; // pointer to the next link, or NULL
};
@ -55,13 +55,13 @@ private:
// ctor, dtor
///////////////////////////////////////////////////////////////////////////////
cBlockList::cBlockList() :
mpBlocks(0)
mpBlocks(0)
{
}
cBlockList::~cBlockList()
{
Clear();
Clear();
}
///////////////////////////////////////////////////////////////////////////////
@ -69,9 +69,9 @@ cBlockList::~cBlockList()
///////////////////////////////////////////////////////////////////////////////
void* cBlockList::Allocate(int size)
{
char* mem = new char[size + sizeof(cBlockLink)];
mpBlocks = new(mem) cBlockLink(mpBlocks);
return mem + sizeof(cBlockLink);
char* mem = new char[size + sizeof(cBlockLink)];
mpBlocks = new(mem) cBlockLink(mpBlocks);
return mem + sizeof(cBlockLink);
}
///////////////////////////////////////////////////////////////////////////////
@ -79,13 +79,13 @@ void* cBlockList::Allocate(int size)
///////////////////////////////////////////////////////////////////////////////
void cBlockList::Clear()
{
while(mpBlocks)
{
cBlockLink* pLink = mpBlocks;
mpBlocks = mpBlocks->Next();
pLink->~cBlockLink();
delete [] (char*)(pLink);
}
while(mpBlocks)
{
cBlockLink* pLink = mpBlocks;
mpBlocks = mpBlocks->Next();
pLink->~cBlockLink();
delete [] (char*)(pLink);
}
}
//-----------------------------------------------------------------------------
@ -96,16 +96,16 @@ void cBlockList::Clear()
// ctor, dtor
///////////////////////////////////////////////////////////////////////////////
cObjectPoolBase::cObjectPoolBase(int objSize, int chunkSize) :
mObjectSize(objSize),
mChunkSize(chunkSize),
mpNextFree(0)
mObjectSize(objSize),
mChunkSize(chunkSize),
mpNextFree(0)
{
}
cObjectPoolBase::~cObjectPoolBase()
{
//TODO -- assert that the number of instances left are 0.
Clear();
//TODO -- assert that the number of instances left are 0.
Clear();
}
///////////////////////////////////////////////////////////////////////////////
@ -113,19 +113,19 @@ cObjectPoolBase::~cObjectPoolBase()
///////////////////////////////////////////////////////////////////////////////
void cObjectPoolBase::AllocNewChunk()
{
ASSERT(mpNextFree == 0);
ASSERT(mpNextFree == 0);
int size = mObjectSize * mChunkSize;
char* pBlock = (char*)mBlockList.Allocate(size);
int size = mObjectSize * mChunkSize;
char* pBlock = (char*)mBlockList.Allocate(size);
char* pLast = pBlock + size - mObjectSize;
for(char* pc = pBlock; pc < pLast; pc += mObjectSize)
{
((cLink*)pc)->mpNext = (cLink*)(pc + mObjectSize);
}
((cLink*)pLast)->mpNext = 0;
char* pLast = pBlock + size - mObjectSize;
for(char* pc = pBlock; pc < pLast; pc += mObjectSize)
{
((cLink*)pc)->mpNext = (cLink*)(pc + mObjectSize);
}
((cLink*)pLast)->mpNext = 0;
mpNextFree = (cLink*)pBlock;
mpNextFree = (cLink*)pBlock;
}

View File

@ -32,8 +32,8 @@
///////////////////////////////////////////////////////////////////////////////
// objectpool.h
//
// cBlockList -- a linked list of blocks of memory
// cObjectPoolBase -- a pool of equal-sized objects; constant time allocation
// cBlockList -- a linked list of blocks of memory
// cObjectPoolBase -- a pool of equal-sized objects; constant time allocation
#ifndef __OBJECTPOOL_H
#define __OBJECTPOOL_H
@ -45,13 +45,13 @@ class cBlockLink;
class cBlockList
{
public:
cBlockList();
~cBlockList();
cBlockList();
~cBlockList();
void* Allocate(int size);
void Clear(); // releases everything in the block list
void* Allocate(int size);
void Clear(); // releases everything in the block list
private:
cBlockLink* mpBlocks; // linked list of blocks
cBlockLink* mpBlocks; // linked list of blocks
};
//-----------------------------------------------------------------------------
@ -60,44 +60,44 @@ private:
class cObjectPoolBase
{
public:
cObjectPoolBase(int objSize, int chunkSize);
~cObjectPoolBase();
// NOTE -- dtor is not virtual; therefore it is potentially dangerous to delete a pointer to
// this class unless you know for sure the dynamic class type has nothing to clean up.
cObjectPoolBase(int objSize, int chunkSize);
~cObjectPoolBase();
// NOTE -- dtor is not virtual; therefore it is potentially dangerous to delete a pointer to
// this class unless you know for sure the dynamic class type has nothing to clean up.
void* Alloc ();
void Free (void* pObj);
void Clear ();
//TODO -- add IsPointerValid()
void* Alloc ();
void Free (void* pObj);
void Clear ();
//TODO -- add IsPointerValid()
private:
void AllocNewChunk(); // get another chunk to use...
void AllocNewChunk(); // get another chunk to use...
struct cLink
{
cLink* mpNext;
};
cBlockList mBlockList;
const int mObjectSize; // how big are the objects?
const int mChunkSize; // how big are the chunks we are allocating?
cLink* mpNextFree; // the next free object
//int mInstanceCount; // number of objects that are currently allocated but not freed.
struct cLink
{
cLink* mpNext;
};
cBlockList mBlockList;
const int mObjectSize; // how big are the objects?
const int mChunkSize; // how big are the chunks we are allocating?
cLink* mpNextFree; // the next free object
//int mInstanceCount; // number of objects that are currently allocated but not freed.
};
//-----------------------------------------------------------------------------
// cObjectPool
// Note -- this template only works for classes that are constructed with their
// default ctor; I don't know how to extend this model to work for non-default
// ctors...
// default ctor; I don't know how to extend this model to work for non-default
// ctors...
//-----------------------------------------------------------------------------
template <class T>
class cObjectPool : public cObjectPoolBase
{
public:
cObjectPool(int chunkSize) : cObjectPoolBase(sizeof(T), chunkSize) {}
cObjectPool(int chunkSize) : cObjectPoolBase(sizeof(T), chunkSize) {}
T* New () { return new(cObjectPoolBase::Alloc()) T(); }
void Delete (T* pObj) { pObj->~T(); Free(pObj); }
T* New () { return new(cObjectPoolBase::Alloc()) T(); }
void Delete (T* pObj) { pObj->~T(); Free(pObj); }
};
//#############################################################################
@ -108,12 +108,12 @@ public:
///////////////////////////////////////////////////////////////////////////////
inline void* cObjectPoolBase::Alloc()
{
if(! mpNextFree)
AllocNewChunk();
if(! mpNextFree)
AllocNewChunk();
cLink* pRtn = mpNextFree;
mpNextFree = mpNextFree->mpNext;
return pRtn;
cLink* pRtn = mpNextFree;
mpNextFree = mpNextFree->mpNext;
return pRtn;
}
///////////////////////////////////////////////////////////////////////////////
@ -121,9 +121,9 @@ inline void* cObjectPoolBase::Alloc()
///////////////////////////////////////////////////////////////////////////////
inline void cObjectPoolBase::Free(void* pObj)
{
cLink* pNew = (cLink*)pObj;
pNew->mpNext = mpNextFree;
mpNextFree = pNew;
cLink* pNew = (cLink*)pObj;
pNew->mpNext = mpNextFree;
mpNextFree = pNew;
}
///////////////////////////////////////////////////////////////////////////////
@ -131,8 +131,8 @@ inline void cObjectPoolBase::Free(void* pObj)
///////////////////////////////////////////////////////////////////////////////
inline void cObjectPoolBase::Clear()
{
mBlockList.Clear();
mpNextFree = 0;
mBlockList.Clear();
mpNextFree = 0;
}

View File

@ -1,109 +0,0 @@
//
// The developer of the original code and/or files is Tripwire, Inc.
// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire,
// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights
// reserved.
//
// This program is free software. The contents of this file are subject
// to the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. You may redistribute it and/or modify it
// only in compliance with the GNU General Public License.
//
// This program is distributed in the hope that it will be useful.
// However, this program is distributed AS-IS WITHOUT ANY
// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// Nothing in the GNU General Public License or any other license to use
// the code or files shall permit you to use Tripwire's trademarks,
// service marks, or other intellectual property without Tripwire's
// prior written consent.
//
// If you have any questions, please contact Tripwire, Inc. at either
// info@tripwire.org or www.tripwire.org.
//
///////////////////////////////////////////////////////////////////////////////
// objectpool_t
#include "stdcore.h"
#include "objectpool.h"
#include "debug.h"
#include "test/test.h"
// this is the struct we will use for testing purposes
struct cDog
{
int i;
char c;
double d;
cDog() : i(53), c('f'), d(3.14) { cDebug d("cDog::cDog"); d.TraceDebug("Dog ctor...\n"); }
~cDog() { cDebug d("cDog::~cDog"); d.TraceDebug("Dog dtor...\n"); }
};
void TestObjectPool()
{
int k, j;
cDebug d("TestObjectPool");
// first, just try the growing properties of the pool
cObjectPoolBase pool(10, 5);
d.TraceDebug("object size = 10, chunk size = 5\n");
for(k=0; k < 12; k++)
{
d.TraceDebug("Allocating...\n");
pool.Alloc();
}
d.TraceDebug("Removing everything...\n");
pool.Clear();
// test the template class
cObjectPool<cDog> dogPool(3);
std::list<cDog*> lDog;
for(j=0; j < 7; j++)
{
lDog.push_back(dogPool.New());
}
std::list<cDog*>::iterator i;
for( i = lDog.begin(); i != lDog.end(); i++)
{
d.TraceDebug("dog contents: %d %c %lf\n", (*i)->i, (*i)->c, (*i)->d);
dogPool.Delete(*i);
}
lDog.clear();
// now, do some random insertions and deletions...
std::vector<void*> vAlloced;
for(k=0; k < 1000; k++)
{
if(rand() % 3 > 0 )
{
// alloc
void* pNew = pool.Alloc();
d.TraceDebug("Allocating %p\n", pNew);
vAlloced.push_back(pNew);
}
else
{
// free
int idx = rand() % vAlloced.size();
std::vector<void*>::iterator vi = vAlloced.begin() + idx;
void* pGone = *vi;
d.TraceDebug("Removing %p\n", pGone);
pool.Free(pGone);
vAlloced.erase(vi);
}
}
d.TraceDebug("Leaving...\n");
}

View File

@ -91,8 +91,8 @@
//--PACKAGE Helpers
#define TSS_Package( pkg ) \
pkg::GetInstance() // Access "the" Package obj
#define TSS_Package( pkg ) \
pkg::GetInstance() // Access "the" Package obj
#define TSS_Dependency( pkg ) \
TSS_Package( pkg ) // Declare a Package Depend.
@ -100,7 +100,7 @@
#define TSS_BeginPackage( pkg ) \
class pkg : public cPackageBase_< TCHAR > \
class pkg : public cPackageBase_< TCHAR > \
{ \
public: \
static pkg& GetInstance();
@ -128,34 +128,34 @@
//--STRINGTABLE Helperfs
#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 \
public: \
Messages::String \
#define TSS_DECLARE_STRINGTABLE \
public: \
Messages::String \
GetString( \
Messages::ConstKeyRef id ) const { \
return m_messages.Get( id ); } \
void LoadStrings(); \
private: \
return m_messages.Get( id ); } \
void LoadStrings(); \
private: \
Messages m_messages // Decare a Stringtable
#ifdef _DEBUG
#define TSS_BeginStringtable( pkg ) \
void pkg::LoadStrings() \
{ cDebug d( #pkg "::LoadStrings()" ); \
void pkg::LoadStrings() \
{ cDebug d( #pkg "::LoadStrings()" ); \
d.TraceDebug("Loading strings for " #pkg " package.\n"); \
Messages::Pair astr[] = { // Define a Stringtable
#else // _DEBUG
#define TSS_BeginStringtable( pkg ) \
void pkg::LoadStrings() \
{ Messages::Pair astr[] = { // Define a Stringtable
void pkg::LoadStrings() \
{ Messages::Pair astr[] = { // Define a Stringtable
#endif // _DEBUG
#define TSS_EndStringtable( pkg ) \
}; m_messages.Put( \
}; m_messages.Put( \
astr, astr + countof(astr) ); } // End define Strintable
@ -175,7 +175,7 @@
// cPackageBase_<CharT> -- Base class for all Package Resources
//-----------------------------------------------------------------------------
// SYNOPSIS:
// This class is the base class for all package representations
// This class is the base class for all package representations
// and, thus, establishes the package contract. It's interface
// is relied on by the Package singleton wrapper, TSS_Package.
// Since part of its contract is that there is only one package
@ -191,15 +191,15 @@
//
// INVARIANTS:
// m_nInstances <= 1
//
//
//
template< class CharT >
class cPackageBase_
{
public:
public:
typedef cMessages_< int, CharT > Messages;
typedef cMessages_< int, CharT > Messages;
void LoadStrings()
{

View File

@ -46,23 +46,23 @@
// For each of these "enumerations" we create unique integers identifying each
// variation. We group similar items together, such as OS_REDHAT and OS_SLACKWARE
#define OS_UNKNOWN 0
#define OS_WIN32 0x0101
#define OS_AIX 0x0401
#define OS_HPUX 0x0501
#define OS_IRIX 0x0601
#define OS_OSF1 0x0701
#define OS_UNKNOWN 0
#define OS_WIN32 0x0101
#define OS_AIX 0x0401
#define OS_HPUX 0x0501
#define OS_IRIX 0x0601
#define OS_OSF1 0x0701
#define COMP_UNKNOWN 0
#define COMP_MSVC 0x0101
#define COMP_KAI_GCC 0x0201
#define COMP_KAI_SUNPRO 0x0202
#define COMP_KAI_GLIBC 0x0203
#define COMP_KAI_VISUALAGE 0x0204
#define COMP_KAI_HPANSIC 0x0205
#define COMP_KAI_IRIX 0x0206
#define COMP_KAI_OSF1ALPHA 0x0207
#define COMP_SUNPRO 0x0301
#define COMP_UNKNOWN 0
#define COMP_MSVC 0x0101
#define COMP_KAI_GCC 0x0201
#define COMP_KAI_SUNPRO 0x0202
#define COMP_KAI_GLIBC 0x0203
#define COMP_KAI_VISUALAGE 0x0204
#define COMP_KAI_HPANSIC 0x0205
#define COMP_KAI_IRIX 0x0206
#define COMP_KAI_OSF1ALPHA 0x0207
#define COMP_SUNPRO 0x0301
//=============================================================================
// Platform detection
@ -93,34 +93,34 @@
#define COMP COMP_KAI_IRIX
#elif defined(_ALPHA)
#define OS OS_OSF1
#define COMP COMP_KAI_OSF1ALPHA
#define OS OS_OSF1
#define COMP COMP_KAI_OSF1ALPHA
#elif defined (_HPUX)
#define OS OS_HPUX
#define COMP COMP_KAI_HPANSIC
#define OS OS_HPUX
#define COMP COMP_KAI_HPANSIC
#else
// OK for OS not to resolve, it's being phased out.
// OK for OS not to resolve, it's being phased out.
// #error Unknown OS
#endif
#if !defined(OS)
// OK for OS not to resolve, it's being phased out.
// OK for OS not to resolve, it's being phased out.
// #error OS definition did not resolve. Check "platform.h".
#endif
/* XXX: COMP may now not resolve, because autoconf may
* detect GCC. This is done in the hopes that all
* COMP detections, and indeed both OS & COMP detechtions
* will eventualy be done automatically.
*
* This means, the former "#if !defined(COMP)" will
* temporarily have to also check the HAVE_[compiler]
* #defines until all compilers are checked by autoconf,
* at which point this can be removed completely.
*
* PH - 20010311
*/
/* XXX: COMP may now not resolve, because autoconf may
* detect GCC. This is done in the hopes that all
* COMP detections, and indeed both OS & COMP detechtions
* will eventualy be done automatically.
*
* This means, the former "#if !defined(COMP)" will
* temporarily have to also check the HAVE_[compiler]
* #defines until all compilers are checked by autoconf,
* at which point this can be removed completely.
*
* PH - 20010311
*/
#if !defined(COMP) && !defined(HAVE_GCC)
#error COMP definition did not resolve. Check "platform.h".
#endif
@ -153,10 +153,10 @@
// OS detection
// Note: Avoid using these if possible (see above)
#define IS_WIN32 (OS == OS_WIN32)
#define IS_AIX (OS == OS_AIX)
#define IS_HPUX (OS == OS_HPUX)
#define IS_IRIX (OS == OS_IRIX)
#define IS_OSF1 (OS == OS_OSF1)
#define IS_AIX (OS == OS_AIX)
#define IS_HPUX (OS == OS_HPUX)
#define IS_IRIX (OS == OS_IRIX)
#define IS_OSF1 (OS == OS_OSF1)
// 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)
@ -179,8 +179,8 @@
// Threading API
// TODO:mdb -- this is not complete or rigorous on the unix side!!!
#define SUPPORTS_WIN32_THREADS IS_WIN32
#define SUPPORTS_POSIX_THREADS (!SUPPORTS_WIN32_THREADS)
#define SUPPORTS_WIN32_THREADS IS_WIN32
#define SUPPORTS_POSIX_THREADS (!SUPPORTS_WIN32_THREADS)
// Miscellaneous
#define FSEEK_TAKES_INT32 IS_UNIX // True if fseek takes 32-bit offsets

View File

@ -54,18 +54,18 @@ RefSet* gpRefCountObj_Objects = 0;
// a way to see what hasn't been accounted for....
struct cRefCountObj_Debug
{
~cRefCountObj_Debug()
{
RefSet::iterator i;
cDebug d("cRefCountObj_Debug");
if(gpRefCountObj_Objects)
{
for(i = gpRefCountObj_Objects->begin(); i != gpRefCountObj_Objects->end(); i++)
{
d.TraceNever("Refrence Counted Object %p still exists\n", *i);
}
}
}
~cRefCountObj_Debug()
{
RefSet::iterator i;
cDebug d("cRefCountObj_Debug");
if(gpRefCountObj_Objects)
{
for(i = gpRefCountObj_Objects->begin(); i != gpRefCountObj_Objects->end(); i++)
{
d.TraceNever("Refrence Counted Object %p still exists\n", *i);
}
}
}
} gRefCountObj_Debug;
#endif // _DEBUG
@ -80,12 +80,12 @@ cRefCountObj::cRefCountObj()
++objectCounter;
++referenceCounter;
cDebug d("cRefCountObj::cRefCountObj");
d.TraceNever("Object Created[%p] %s\n", this, typeid(*this).name());
cDebug d("cRefCountObj::cRefCountObj");
d.TraceNever("Object Created[%p] %s\n", this, typeid(*this).name());
if(! gpRefCountObj_Objects)
gpRefCountObj_Objects = new RefSet;
gpRefCountObj_Objects->insert(this);
if(! gpRefCountObj_Objects)
gpRefCountObj_Objects = new RefSet;
gpRefCountObj_Objects->insert(this);
#endif
}
@ -97,20 +97,20 @@ cRefCountObj::~cRefCountObj()
#ifdef _DEBUG
--objectCounter;
cDebug d("cRefCountObj::~cRefCountObj");
d.TraceNever("Object Destroyed[%p] %s Objects Left = %d\n", this, typeid(*this).name(), objectCounter);
if(objectCounter == 0)
{
d.TraceDebug("****** All Reference Counted Objects Destroyed! ******\n") ;
}
ASSERT(gpRefCountObj_Objects);
RefSet::const_iterator i = gpRefCountObj_Objects->find(this);
ASSERT(i != gpRefCountObj_Objects->end());
gpRefCountObj_Objects->erase(this);
if(gpRefCountObj_Objects->size() == 0)
cDebug d("cRefCountObj::~cRefCountObj");
d.TraceNever("Object Destroyed[%p] %s Objects Left = %d\n", this, typeid(*this).name(), objectCounter);
if(objectCounter == 0)
{
delete gpRefCountObj_Objects;
d.TraceDebug("****** All Reference Counted Objects Destroyed! ******\n") ;
}
ASSERT(gpRefCountObj_Objects);
RefSet::const_iterator i = gpRefCountObj_Objects->find(this);
ASSERT(i != gpRefCountObj_Objects->end());
gpRefCountObj_Objects->erase(this);
if(gpRefCountObj_Objects->size() == 0)
{
delete gpRefCountObj_Objects;
gpRefCountObj_Objects = 0;
}
@ -135,7 +135,7 @@ void cRefCountObj::AddRef() const
void cRefCountObj::Release() const
{
if (this == 0)
if (this == 0)
return;
if (--mRefCount == 0)
@ -150,6 +150,6 @@ void cRefCountObj::Release() const
void cRefCountObj::Delete() const
{
delete this;
delete this;
}

View File

@ -67,13 +67,13 @@ public:
virtual void AddRef() const;
virtual void Release() const;
int GetRefCount() const { return mRefCount; }
// sometimes it is useful to know an object's refrence
int GetRefCount() const { return mRefCount; }
// sometimes it is useful to know an object's refrence
protected:
virtual ~cRefCountObj();
virtual void Delete() const;
// override this if you don't want to be destroyed by "delete this"!
virtual void Delete() const;
// override this if you don't want to be destroyed by "delete this"!
private:
mutable int mRefCount;

View File

@ -67,13 +67,13 @@ template< class KEY, class CHR > class cMessages_;
// Used to maintain a table of resources that are indexed by KEY
// type values. The <REZ> type can be any valid type that is
// assignable.
//
//
// CONSTRAINTS:
// <KEY> must be a valid key type for the std::map concept
// <REZ> must be a valid value type for the std::map concept.
//
//
// INVARIANTS:
//
//
//
template< class KeyT, class RscT >
class cResources_
@ -135,7 +135,7 @@ class cResources_
//-----------------------------------------------------------------------------
// SYNOPSIS:
// Specialization of cResources_<KEY,REZ> to store message strings
// instead of generalized resource objects. In the future this can
// instead of generalized resource objects. In the future this can
// be refactored to use message objects so that they can come from
// a dynamic source (i.e., not a string-literal) such as persistant
// storage or some algorithm based on the concatenation of elements.
@ -145,9 +145,9 @@ class cResources_
// not allowing the client to expect a specific character sequence
// representation, such as the near ubiquitous const char*. For
// example:
//
//
// const char* psz = messages.GetAnsi( IDS_SOMESTRING );
//
//
// The above call requires the caller to be responsible for memory
// resources in the case of a conversion. However, there is no
// clear way to know up front how many bytes will be required.
@ -155,14 +155,14 @@ class cResources_
// memory within cMessages and require the caller to release the
// the resources when they are done with the message. If we instead
// require calls in the following form:
//
//
// std::string str = messages.GetAnsi( IDS_SOMESTRING );
//
//
// We can allows assume proper resource use regardless of whether
// a simple character pointer is returned or newly allocated
// resources used to convert the stored message.
//
//
//
// CONSTRAINTS:
// As with all classes which manipulate character sequences, CHAR
// must be a valid character type as defined by the STDCPP standard.
@ -425,7 +425,7 @@ Message_Class::GetWide( ConstKeyRef id ) const
// cMessages_<char & wchar_t> -- Specializations
//-----------------------------------------------------------------------------
// SYNOPSIS:
// MSVC does not yet support specializations. As a compromise, we fully
// MSVC does not yet support specializations. As a compromise, we fully
// specialize on TCHR but assume a key type of "const int".
//
@ -456,7 +456,7 @@ class cMessages_<ENUM_TYPE, char> :
{
Value msg = Resources::Get( id );
return ( msg != DefaultValueRef() )
? String( msg )
? String( msg )
: String();
}

View File

@ -78,9 +78,9 @@ class iSerializer;
class iSerializable
{
public:
virtual void Read (iSerializer* pSerializer, int32 version = 0) = 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.
virtual void Read (iSerializer* pSerializer, int32 version = 0) = 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.
virtual ~iSerializable() {}
};
@ -88,16 +88,16 @@ public:
class iTypedSerializable : public iTyped, public iSerializable
{
public:
typedef iTypedSerializable* (*CreateFunc)();
// Pointer to a function that creates an empty version of each typed serializable object
typedef iTypedSerializable* (*CreateFunc)();
// Pointer to a function that creates an empty version of each typed serializable object
virtual int32 Version() const = 0;
// Return the current version of that this serializable object writes.
// As a convention version number should be (major_version << 16) | minor_version.
virtual int32 Version() const = 0;
// Return the current version of that this serializable object writes.
// 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 int16 MajorVersion(int32 version) { return (int16)((uint32)version >> 16); }
static int16 MinorVersion(int32 version) { return (int16)version; }
static int32 MkVersion(int16 major, int16 minor) { 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() {}
};
@ -105,21 +105,21 @@ public:
//////////////////////////////
// convenience macros
#define DECLARE_TYPEDSERIALIZABLE() \
DECLARE_TYPED() \
public: \
static iTypedSerializable* Create(); \
virtual int32 Version() const;
DECLARE_TYPED() \
public: \
static iTypedSerializable* Create(); \
virtual int32 Version() const;
#define IMPLEMENT_TYPEDSERIALIZABLE(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \
IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \
iTypedSerializable* CLASS::Create() \
{ \
return new CLASS; \
} \
int32 CLASS::Version() const \
{ \
return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \
}
IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \
iTypedSerializable* CLASS::Create() \
{ \
return new CLASS; \
} \
int32 CLASS::Version() const \
{ \
return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \
}
#endif // __SERIALIZABLE_H

View File

@ -45,78 +45,78 @@
// eSerializer::GetMsg -- Overloaded method for returning an error message.
/*virtual*/ TSTRING eSerializer::GetMsg() const
{
TSTRING ret;
TSTRING ret;
if( !eSerializer::mDataSource.empty() )
{
if( !eSerializer::mDataSource.empty() )
{
ret = mMsg;
switch( eSerializer::mSourceType )
{
case TY_UNDEFINED:
ret.append( mDataSource );
break;
case TY_FILE:
ret.append( _T("\nFile: ") );
ret.append( mDataSource );
break;
case TY_TEMPFILE:
ret.append( _T("\nTemporary File: ") );
ret.append( mDataSource );
break;
case TY_MEMORY:
ret.append( _T("\nMemory Block: ") ); //uhhh...??
ret.append( mDataSource );
break;
case TY_PIPE:
ret.append( _T("\nNamed Pipe: "));
ret.append( mDataSource );
break;
case TY_SOCKET:
ret.append( _T("\nNetwork Socket: "));
ret.append( mDataSource );
break;
default:
ret.append( _T("\n"));
ret.append( mDataSource );
break;
}
}
else
{
switch( eSerializer::mSourceType )
{
case TY_UNDEFINED:
ret.append( mDataSource );
break;
case TY_FILE:
ret.append( _T("\nFile: ") );
ret.append( mDataSource );
break;
case TY_TEMPFILE:
ret.append( _T("\nTemporary File: ") );
ret.append( mDataSource );
break;
case TY_MEMORY:
ret.append( _T("\nMemory Block: ") ); //uhhh...??
ret.append( mDataSource );
break;
case TY_PIPE:
ret.append( _T("\nNamed Pipe: "));
ret.append( mDataSource );
break;
case TY_SOCKET:
ret.append( _T("\nNetwork Socket: "));
ret.append( mDataSource );
break;
default:
ret.append( _T("\n"));
ret.append( mDataSource );
break;
}
}
else
{
// Just use the base class method...
ret = eError::GetMsg();
}
return ret;
ret = eError::GetMsg();
}
return ret;
}
/*
eSerializer::eSerializer(ErrorNum errNum, const TSTRING& msg) :
eError(errNum, msg)
eError(errNum, msg)
{
}
const TSTRING& eSerializer::GetMsg() const
const TSTRING& eSerializer::GetMsg() const
{
if((mErrorNum < 0) || (mErrorNum >= E_NUMITEMS))
{
// I don't know what this error number is; just use the base class implementation
return eError::GetMsg();
}
if((mErrorNum < 0) || (mErrorNum >= E_NUMITEMS))
{
// I don't know what this error number is; just use the base class implementation
return eError::GetMsg();
}
static TSTRING message;
static const TCHAR* reasonStrings[] = { _T("The serializer encountered an unknown type"),
_T("Invlaid input stream format for serializer"),
_T("Archive error"),
_T("Version Mismatch"),
_T("Invalid Reason") };
static TSTRING message;
static const TCHAR* reasonStrings[] = { _T("The serializer encountered an unknown type"),
_T("Invlaid input stream format for serializer"),
_T("Archive error"),
_T("Version Mismatch"),
_T("Invalid Reason") };
message = reasonStrings[mErrorNum];
message += _T(" : ");
message += mMsg;
message = reasonStrings[mErrorNum];
message += _T(" : ");
message += mMsg;
return message;
return message;
}

View File

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

View File

@ -38,25 +38,25 @@
#include "crc32.h"
// static members
cSerializerImpl::SerMap cSerializerImpl::mSerCreateMap ;
cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap ;
cSerializerImpl::SerMap cSerializerImpl::mSerCreateMap ;
cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap ;
// RAD:09/01/99 -- No longer needed!
///////////////////////////////////////////////////////////////////////////////
// util_TstrToStr -- converts the passed in tstring into a narrow string. maxSize
// indicates the size of the narrow buffer
// indicates the size of the narrow buffer
///////////////////////////////////////////////////////////////////////////////
// static inline void util_TstrToStr(char* pStr, const TCHAR* pTstr, int maxSize)
// {
// #ifdef _UNICODE
// ASSERT( maxSize >= wcstombs( 0, pTstr
// wcstombs(pStr, pTstr, maxSize);
// #else
// strncpy( pStr, pTstr, maxSize );
// #endif
// }
//
// static inline void util_TstrToStr(char* pStr, const TCHAR* pTstr, int maxSize)
// {
// #ifdef _UNICODE
// ASSERT( maxSize >= wcstombs( 0, pTstr
// wcstombs(pStr, pTstr, maxSize);
// #else
// strncpy( pStr, pTstr, maxSize );
// #endif
// }
//
///////////////////////////////////////////////////////////////////////////////
@ -64,9 +64,9 @@ cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap ;
///////////////////////////////////////////////////////////////////////////////
static uint32 util_GetCRC( const cType& type )
{
//
// convert this to narrow...
//
//
// convert this to narrow...
//
// NOTE:RAD -- Fixed bug when going from TCHAR is Wide to Multibyte
// 09/01/99 - Increased performance by returning byte len instead of
@ -77,7 +77,7 @@ static uint32 util_GetCRC( const cType& type )
#ifdef _UNICODE
char sz[256];
const uint8* pszType = (const uint8*)(&sz[0]);
const uint8* pszType = (const uint8*)(&sz[0]);
const wchar_t* wsz = type.AsString();
ASSERT( countof(sz) >= ::wcstombs( 0, wsz, size_t(-1) ) );
@ -102,24 +102,24 @@ static uint32 util_GetCRC( const cType& type )
ASSERT( pszType && *pszType );
//
// calculate the crc...
//
CRC_INFO crc;
crcInit( crc );
// calculate the crc...
//
CRC_INFO crc;
crcInit( crc );
crcUpdate( crc, pszType, nBytes );
crcFinit( crc );
crcFinit( crc );
return crc.crc;
return crc.crc;
}
//#############################################################################
// class cSerializerImpl
//#############################################################################
cSerializerImpl::cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName) :
mpArchive(&archive),
mMode(action),
mbInit(false),
mFileName( fileName )
mpArchive(&archive),
mMode(action),
mbInit(false),
mFileName( fileName )
{
}
@ -129,13 +129,13 @@ cSerializerImpl::~cSerializerImpl()
bool cSerializerImpl::IsWriting() const
{
return (mMode == S_WRITE);
return (mMode == S_WRITE);
}
///////////////////////////////////////////////////////////////////////////////
// static object registration functions; Exactly one of these should be called for
// every object that is to be serialized.
// every object that is to be serialized.
///////////////////////////////////////////////////////////////////////////////
// TODO:dmb - following line doesn't do anything???
@ -143,49 +143,49 @@ bool cSerializerImpl::IsWriting() const
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() )
{
// duplicate entry!
//
ASSERT( false );
TOSTRINGSTREAM str;
str << _T("Duplicate entry in type table: ") << type.AsString() << std::endl;
throw eInternal(str.str());
}
cSerializerImpl::mSerCreateMap[crc] = pFunc;
if( cSerializerImpl::mSerCreateMap.find( crc ) != cSerializerImpl::mSerCreateMap.end() )
{
// duplicate entry!
//
ASSERT( false );
TOSTRINGSTREAM str;
str << _T("Duplicate entry in type table: ") << type.AsString() << std::endl;
throw eInternal(str.str());
}
cSerializerImpl::mSerCreateMap[crc] = 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() )
{
// duplicate entry!
//
ASSERT( false );
TOSTRINGSTREAM str;
str << _T("Duplicate entry in type table: ") << type.AsString() << std::ends;
throw eInternal(str.str());
}
cSerializerImpl::mSerRefCountCreateMap[crc] = pFunc;
if( cSerializerImpl::mSerRefCountCreateMap.find( crc ) != cSerializerImpl::mSerRefCountCreateMap.end() )
{
// duplicate entry!
//
ASSERT( false );
TOSTRINGSTREAM str;
str << _T("Duplicate entry in type table: ") << type.AsString() << std::ends;
throw eInternal(str.str());
}
cSerializerImpl::mSerRefCountCreateMap[crc] = pFunc;
}
///////////////////////////////////////////////////////////////////////////////
// Init -- the job of init is to clear out the RefCountObj table, fill out the
// mTypeArray, and and write the header information
// mTypeArray, and and write the header information
///////////////////////////////////////////////////////////////////////////////
void cSerializerImpl::Init()
{
cDebug d("cSerializerImpl::Init");
d.TraceDetail("Entering; IsWriting = %s\n", IsWriting() ? "true" : "false");
cDebug d("cSerializerImpl::Init");
d.TraceDetail("Entering; IsWriting = %s\n", IsWriting() ? "true" : "false");
mRefCtObjTbl.Clear();
mRefCtObjTbl.Clear();
mbInit = true;
mbInit = true;
}
///////////////////////////////////////////////////////////////////////////////
@ -193,9 +193,9 @@ void cSerializerImpl::Init()
///////////////////////////////////////////////////////////////////////////////
void cSerializerImpl::Finit()
{
cDebug d("cSerializerImpl::Finit");
d.TraceDetail("Exiting; IsWriting = %s\n", IsWriting() ? "true" : "false");
mbInit = false;
cDebug d("cSerializerImpl::Finit");
d.TraceDetail("Exiting; IsWriting = %s\n", IsWriting() ? "true" : "false");
mbInit = false;
}
///////////////////////////////////////////////////////////////////////////////
@ -203,168 +203,168 @@ void cSerializerImpl::Finit()
///////////////////////////////////////////////////////////////////////////////
void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj)
{
ASSERT(mbInit);
ASSERT(IsWriting());
cDebug d("cSerializerImpl::WriteObjectDynCreate");
// CurrentPos() only works with bidir archive
//d.TraceDetail("Entering... Archive Offset = %d\n", mpArchive->CurrentPos());
d.TraceDetail(_T(" Object Type = %s\n"), pObj->GetType().AsString());
// first, we write out the header, which consists of the following:
// uint32 crc of the object's type
// int32 version of stored data
// int32 size of the chunk (counting from this point; not including the previous int32
// int32 index into mRefCountObjTbl, or 0 if it isn't refrence counted.
// if the index already exists, then no data follows; a refrence
// should just be added to the existing object.
ASSERT(mpArchive != 0);
ASSERT(mbInit);
ASSERT(IsWriting());
cDebug d("cSerializerImpl::WriteObjectDynCreate");
// CurrentPos() only works with bidir archive
//d.TraceDetail("Entering... Archive Offset = %d\n", mpArchive->CurrentPos());
d.TraceDetail(_T(" Object Type = %s\n"), pObj->GetType().AsString());
// first, we write out the header, which consists of the following:
// uint32 crc of the object's type
// int32 version of stored data
// int32 size of the chunk (counting from this point; not including the previous int32
// int32 index into mRefCountObjTbl, or 0 if it isn't refrence counted.
// if the index already exists, then no data follows; a refrence
// should just be added to the existing object.
ASSERT(mpArchive != 0);
// get the ident for this class type
//
uint32 crc = util_GetCRC( pObj->GetType() );
// get the ident for this class type
//
uint32 crc = util_GetCRC( pObj->GetType() );
//
// make sure this type is registered, and figure out if it is refrence counted
//
SerRefCountMap::iterator i = mSerRefCountCreateMap.find( crc );
bool bRefCount = true;
if( i == mSerRefCountCreateMap.end() )
{
//
// maybe it is not refrence counted...
//
SerMap::iterator si = mSerCreateMap.find( crc );
if( si == mSerCreateMap.end() )
{
d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString());
ThrowAndAssert(eSerializerUnknownType( pObj->GetType().AsString(), mFileName, eSerializer::TY_FILE ));
}
bRefCount = false;
}
//
// make sure this type is registered, and figure out if it is refrence counted
//
SerRefCountMap::iterator i = mSerRefCountCreateMap.find( crc );
bool bRefCount = true;
if( i == mSerRefCountCreateMap.end() )
{
//
// maybe it is not refrence counted...
//
SerMap::iterator si = mSerCreateMap.find( crc );
if( si == mSerCreateMap.end() )
{
d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString());
ThrowAndAssert(eSerializerUnknownType( pObj->GetType().AsString(), mFileName, eSerializer::TY_FILE ));
}
bRefCount = false;
}
mpArchive->WriteInt32(crc);
mpArchive->WriteInt32(pObj->Version());
// write a placeholder for the size; we will come back and fill in the right value later...
mpArchive->WriteInt32(0xffffffff);
if(bRefCount)
{
// see if the object has already been serialized...
int idx;
if((idx = mRefCtObjTbl.Lookup(static_cast<const iSerRefCountObj*>(pObj))) == 0)
{
// it is not in the table yet; add it and serialize the object
idx = mRefCtObjTbl.Add(static_cast<const iSerRefCountObj*>(pObj));
d.TraceDetail("Object [%d] written for first time...\n", idx);
mpArchive->WriteInt32(idx);
pObj->Write(this);
}
else
{
// since it is already in the table, just write the index number
d.TraceDetail("Object [%d] already serialized; incrementing refrence count.\n", idx);
mpArchive->WriteInt32(idx);
}
}
else
{
// not reference counted ... just write 0
mpArchive->WriteInt32(0);
// ... then write the object.
pObj->Write(this);
mpArchive->WriteInt32(crc);
mpArchive->WriteInt32(pObj->Version());
// write a placeholder for the size; we will come back and fill in the right value later...
mpArchive->WriteInt32(0xffffffff);
if(bRefCount)
{
// see if the object has already been serialized...
int idx;
if((idx = mRefCtObjTbl.Lookup(static_cast<const iSerRefCountObj*>(pObj))) == 0)
{
// it is not in the table yet; add it and serialize the object
idx = mRefCtObjTbl.Add(static_cast<const iSerRefCountObj*>(pObj));
d.TraceDetail("Object [%d] written for first time...\n", idx);
mpArchive->WriteInt32(idx);
pObj->Write(this);
}
else
{
// since it is already in the table, just write the index number
d.TraceDetail("Object [%d] already serialized; incrementing refrence count.\n", idx);
mpArchive->WriteInt32(idx);
}
}
else
{
// not reference counted ... just write 0
mpArchive->WriteInt32(0);
// ... then write the object.
pObj->Write(this);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// ReadObjectDynCreate
///////////////////////////////////////////////////////////////////////////////
iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
{
cDebug d("cSerializerImpl::ReadObjectDynCreate");
//d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos());
cDebug d("cSerializerImpl::ReadObjectDynCreate");
//d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos());
int32 size, objIdx;
uint32 crc;
// first, get the type...
mpArchive->ReadInt32(reinterpret_cast<int32&>(crc));
int32 size, objIdx;
uint32 crc;
// first, get the type...
mpArchive->ReadInt32(reinterpret_cast<int32&>(crc));
// read in the version
int32 version;
mpArchive->ReadInt32(version);
// read in the version
int32 version;
mpArchive->ReadInt32(version);
// read in the size and the index...
mpArchive->ReadInt32(size);
// read in the size and the index...
mpArchive->ReadInt32(size);
// Save the position so we can seek correctly later on
//int64 sizePos = mpArchive->CurrentPos();
// Save the position so we can seek correctly later on
//int64 sizePos = mpArchive->CurrentPos();
mpArchive->ReadInt32(objIdx);
if(objIdx == 0)
{
// the object is not reference counted; create and read in the object
// first, we need to create the object.
SerMap::iterator si;
si = mSerCreateMap.find(crc);
if(si == mSerCreateMap.end())
{
// unable to find the creation function...
d.TraceError("Unable to find creation function for non-ref counted object %d\n", crc);
TOSTRINGSTREAM str;
mpArchive->ReadInt32(objIdx);
if(objIdx == 0)
{
// the object is not reference counted; create and read in the object
// first, we need to create the object.
SerMap::iterator si;
si = mSerCreateMap.find(crc);
if(si == mSerCreateMap.end())
{
// unable to find the creation function...
d.TraceError("Unable to find creation function for non-ref counted object %d\n", crc);
TOSTRINGSTREAM str;
#ifdef _DEBUG
// Let's only report the actual crc in debug mode
str << (int32)crc << std::ends;
str << (int32)crc << std::ends;
#endif
ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE));
}
iTypedSerializable* pObj = ((*si).second)();
d.TraceDetail("Created non-ref counted object %s(%p)\n", pObj->GetType().AsString(), pObj);
pObj->Read(this, version);
ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE));
}
iTypedSerializable* pObj = ((*si).second)();
d.TraceDetail("Created non-ref counted object %s(%p)\n", pObj->GetType().AsString(), pObj);
pObj->Read(this, version);
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
return pObj;
}
else
{
// refrence counted...
iSerRefCountObj* pObj;
pObj = mRefCtObjTbl.Lookup(objIdx);
if(pObj == NULL)
{
// not in table yet...first find the creation function
SerRefCountMap::iterator rci;
rci = mSerRefCountCreateMap.find(crc);
if(rci == mSerRefCountCreateMap.end())
{
// unable to find the creation function...
d.TraceError("Unable to find creation function for ref counted object %d\n", crc);
TOSTRINGSTREAM str;
str << (int32)crc << std::ends;
ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE));
}
pObj = ((*rci).second)();
d.TraceDetail("Creating Ref-Coutnted object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj);
pObj->Read(this);
mRefCtObjTbl.Add(pObj, objIdx);
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
return pObj;
}
else
{
// refrence counted...
iSerRefCountObj* pObj;
pObj = mRefCtObjTbl.Lookup(objIdx);
if(pObj == NULL)
{
// not in table yet...first find the creation function
SerRefCountMap::iterator rci;
rci = mSerRefCountCreateMap.find(crc);
if(rci == mSerRefCountCreateMap.end())
{
// unable to find the creation function...
d.TraceError("Unable to find creation function for ref counted object %d\n", crc);
TOSTRINGSTREAM str;
str << (int32)crc << std::ends;
ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE));
}
pObj = ((*rci).second)();
d.TraceDetail("Creating Ref-Coutnted object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj);
pObj->Read(this);
mRefCtObjTbl.Add(pObj, objIdx);
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
return pObj;
}
else
{
// already serialized; just return this object.
d.TraceDetail("Adding refrence to previously serialized object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj);
pObj->AddRef();
}
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
return pObj;
}
else
{
// already serialized; just return this object.
d.TraceDetail("Adding refrence to previously serialized object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj);
pObj->AddRef();
}
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
return pObj;
}
return pObj;
}
}
///////////////////////////////////////////////////////////////////////////////
@ -372,102 +372,102 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
///////////////////////////////////////////////////////////////////////////////
void cSerializerImpl::WriteObject(const iTypedSerializable* pObj)
{
ASSERT(pObj != 0);
//ASSERT(mbInit); // this isn't needed if we are not writing the type array
ASSERT(IsWriting());
cDebug d("cSerializerImpl::WriteObject");
//d.TraceDetail("Entering... Archive Offset = %d\n", mpArchive->CurrentPos());
d.TraceDetail(" Object Type = %s\n", pObj->GetType().AsString());
// first, we write out the header, which consists of the following:
// int32 refrence into mTypeArray, indicating the object's type
// int32 version of stored data
// int32 size of the chunk (counting from this point; not including the previous int32
// data the object data
ASSERT(mpArchive != 0);
ASSERT(pObj != 0);
//ASSERT(mbInit); // this isn't needed if we are not writing the type array
ASSERT(IsWriting());
cDebug d("cSerializerImpl::WriteObject");
//d.TraceDetail("Entering... Archive Offset = %d\n", mpArchive->CurrentPos());
d.TraceDetail(" Object Type = %s\n", pObj->GetType().AsString());
// first, we write out the header, which consists of the following:
// int32 refrence into mTypeArray, indicating the object's type
// int32 version of stored data
// int32 size of the chunk (counting from this point; not including the previous int32
// data the object data
ASSERT(mpArchive != 0);
// 5Nov 98 mdb -- I am removing the read and write of type info for this method; it is never used, since
// 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
// when it is read back in)
/* int i = 0;
for(; i < mTypeArray.size(); i++)
{
if(pObj->GetType() == *mTypeArray[i])
{
// aha! this is it!
break;
}
}
if(i == mTypeArray.size())
{
// the type was not registered;
// a debate exists in my mind as to whether this should be an exception or an assertion -- mdb
d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString());
ThrowAndAssert(eSerializerUnknownType(pObj->GetType().AsString()));
}
mpArchive->WriteInt32(i);
// 5Nov 98 mdb -- I am removing the read and write of type info for this method; it is never used, since
// 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
// when it is read back in)
/* int i = 0;
for(; i < mTypeArray.size(); i++)
{
if(pObj->GetType() == *mTypeArray[i])
{
// aha! this is it!
break;
}
}
if(i == mTypeArray.size())
{
// the type was not registered;
// a debate exists in my mind as to whether this should be an exception or an assertion -- mdb
d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString());
ThrowAndAssert(eSerializerUnknownType(pObj->GetType().AsString()));
}
mpArchive->WriteInt32(i);
*/
mpArchive->WriteInt32(0); // place holder for type array index
mpArchive->WriteInt32(pObj->Version());
// write a placeholder for the size; we will come back and fill in the right value later...
//int64 sizePos = mpArchive->CurrentPos();
mpArchive->WriteInt32(0xffffffff);
// write out the object!
pObj->Write(this);
mpArchive->WriteInt32(0); // place holder for type array index
mpArchive->WriteInt32(pObj->Version());
// write a placeholder for the size; we will come back and fill in the right value later...
//int64 sizePos = mpArchive->CurrentPos();
mpArchive->WriteInt32(0xffffffff);
// write out the object!
pObj->Write(this);
// finally, we need to go back and patch up the size...
//int64 returnPos = mpArchive->CurrentPos();
//mpArchive->Seek(sizePos, cBidirArchive::BEGINNING);
//mpArchive->WriteInt32((int32)(returnPos - sizePos - sizeof(int32)));
//mpArchive->Seek(returnPos, cBidirArchive::BEGINNING);
// finally, we need to go back and patch up the size...
//int64 returnPos = mpArchive->CurrentPos();
//mpArchive->Seek(sizePos, cBidirArchive::BEGINNING);
//mpArchive->WriteInt32((int32)(returnPos - sizePos - sizeof(int32)));
//mpArchive->Seek(returnPos, cBidirArchive::BEGINNING);
}
void cSerializerImpl::ReadObject(iTypedSerializable* pObj)
{
cDebug d("cSerializerImpl::ReadObjectDynCreate");
//d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos());
cDebug d("cSerializerImpl::ReadObjectDynCreate");
//d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos());
// NOTE -- type index stuff is gone; see the comment in WriteObject()
int32 /*typeIdx,*/ size;
// first, get the type...
/*
mpArchive->ReadInt32(typeIdx);
if((typeIdx < 0) || (typeIdx >= mTypeArray.size()))
{
// unknown type index!
d.TraceError("Encountered bad index into TypeArray: %d\n", typeIdx);
ThrowAndAssert(eSerializerInputStremTypeArray());
}
const cType* pType = mTypeArray[typeIdx];
*/
// NOTE -- type index stuff is gone; see the comment in WriteObject()
int32 /*typeIdx,*/ size;
// first, get the type...
/*
mpArchive->ReadInt32(typeIdx);
if((typeIdx < 0) || (typeIdx >= mTypeArray.size()))
{
// unknown type index!
d.TraceError("Encountered bad index into TypeArray: %d\n", typeIdx);
ThrowAndAssert(eSerializerInputStremTypeArray());
}
const cType* pType = mTypeArray[typeIdx];
*/
// read in the version
int32 dummy, version;
mpArchive->ReadInt32(dummy); // old type array index
mpArchive->ReadInt32(version);
// read in the version
int32 dummy, version;
mpArchive->ReadInt32(dummy); // old type array index
mpArchive->ReadInt32(version);
// read in the size and the index...
mpArchive->ReadInt32(size);
// read in the size and the index...
mpArchive->ReadInt32(size);
// use the size to assert that the file format is correct
if(size != (int)0xffffffff)
{
// unknown type index!
d.TraceError("Encountered bad size: %d\n", size);
ThrowAndAssert(eSerializerInputStremTypeArray(_T(""), mFileName, eSerializer::TY_FILE));
}
// use the size to assert that the file format is correct
if(size != (int)0xffffffff)
{
// unknown type index!
d.TraceError("Encountered bad size: %d\n", size);
ThrowAndAssert(eSerializerInputStremTypeArray(_T(""), mFileName, eSerializer::TY_FILE));
}
// remember current position
//int64 sizePos = mpArchive->CurrentPos();
// remember current position
//int64 sizePos = mpArchive->CurrentPos();
// read in the object!
pObj->Read(this, version);
// read in the object!
pObj->Read(this, version);
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
// seek past this object in case filepos is not correct!
//mpArchive->Seek(sizePos + size, cBidirArchive::BEGINNING);
}
@ -476,52 +476,52 @@ void cSerializerImpl::ReadObject(iTypedSerializable* pObj)
///////////////////////////////////////////////////////////////////////////////
void cSerializerImpl::ReadInt16(int16& ret)
{
mpArchive->ReadInt16(ret);
mpArchive->ReadInt16(ret);
}
void cSerializerImpl::ReadInt32(int32& ret)
{
mpArchive->ReadInt32(ret);
mpArchive->ReadInt32(ret);
}
void cSerializerImpl::ReadInt64(int64& ret)
{
mpArchive->ReadInt64(ret);
mpArchive->ReadInt64(ret);
}
void cSerializerImpl::ReadString(TSTRING& ret)
{
mpArchive->ReadString(ret);
mpArchive->ReadString(ret);
}
int cSerializerImpl::ReadBlob(void* pBlob, int count)
{
return mpArchive->ReadBlob(pBlob, count);
return mpArchive->ReadBlob(pBlob, count);
}
void cSerializerImpl::WriteInt16(int16 i)
{
mpArchive->WriteInt16(i);
mpArchive->WriteInt16(i);
}
void cSerializerImpl::WriteInt32(int32 i)
{
mpArchive->WriteInt32(i);
mpArchive->WriteInt32(i);
}
void cSerializerImpl::WriteInt64(int64 i)
{
mpArchive->WriteInt64(i);
mpArchive->WriteInt64(i);
}
void cSerializerImpl::WriteString(const TSTRING& s)
{
mpArchive->WriteString(s);
mpArchive->WriteString(s);
}
void cSerializerImpl::WriteBlob(const void* pBlob, int count)
{
mpArchive->WriteBlob(pBlob, count);
mpArchive->WriteBlob(pBlob, count);
}
///////////////////////////////////////////////////////////////////////////////
@ -529,6 +529,6 @@ void cSerializerImpl::WriteBlob(const void* pBlob, int count)
///////////////////////////////////////////////////////////////////////////////
TSTRING cSerializerImpl::GetFileName() const
{
return mFileName;
return mFileName;
}

View File

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

View File

@ -39,35 +39,35 @@ namespace {
template<class FROM, class TO>
int64 CopyImpl(TO* pTo, FROM* pFrom, int64 amt)
{
enum { BUF_SIZE = 8192 };
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
// only take int's as their size parameter - dmb
int amtToRead = amtLeft > BUF_SIZE ? BUF_SIZE : (int)amtLeft;
int amtRead = pFrom->ReadBlob(buf, amtToRead );
amtLeft -= amtRead;
pTo->WriteBlob(buf, amtRead);
if(amtRead < amtToRead)
break;
}
int amtToRead = amtLeft > BUF_SIZE ? BUF_SIZE : (int)amtLeft;
int amtRead = pFrom->ReadBlob(buf, amtToRead );
amtLeft -= amtRead;
pTo->WriteBlob(buf, amtRead);
if(amtRead < amtToRead)
break;
}
// return the amount copied ...
return (amt - amtLeft);
// return the amount copied ...
return (amt - amtLeft);
}
}
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 )
{
return CopyImpl( pDest, pSrc, amt );
return CopyImpl( pDest, pSrc, amt );
}

View File

@ -44,10 +44,10 @@ class iSerializer;
class cSerializerUtil
{
public:
static int64 Copy( iSerializer* pDest, cArchive* 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
// throw exceptions on error; the return value is the amount that was copied.
static int64 Copy( iSerializer* pDest, cArchive* 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
// throw exceptions on error; the return value is the amount that was copied.
};
#endif

View File

@ -57,8 +57,8 @@ public:
std::string mString;
virtual ~cSerializableNString() {};
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
DECLARE_TYPEDSERIALIZABLE()
};
@ -72,8 +72,8 @@ public:
std::string mString;
virtual ~cSerializableWString() {};
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
DECLARE_TYPEDSERIALIZABLE()
};

View File

@ -36,7 +36,7 @@
/*
* sha.c
*
* signature function hook for SHA.
* signature function hook for SHA.
*
* Gene Kim
* Purdue University
@ -175,7 +175,7 @@ void shsTransform(SHS_INFO *shsInfo)
/* Step A. Copy the data buffer into the local work buffer */
for( i = 0; i < 16; i++ )
W[ i ] = shsInfo->data[ i ];
W[ i ] = shsInfo->data[ i ];
/* Step B. Expand the 16 words into 64 temporary data words */
expand( 16 ); expand( 17 ); expand( 18 ); expand( 19 ); expand( 20 );
@ -244,10 +244,10 @@ static void byteReverse(uint32* buffer, int byteCount)
byteCount /= sizeof( uint32 );
for( count = 0; count < byteCount; count++ )
{
value = ( buffer[ count ] << 16 ) | ( buffer[ count ] >> 16 );
buffer[ count ] = ( ( value & 0xFF00FF00L ) >> 8 ) | ( ( value & 0x00FF00FFL ) << 8 );
}
{
value = ( buffer[ count ] << 16 ) | ( buffer[ count ] >> 16 );
buffer[ count ] = ( ( value & 0xFF00FF00L ) >> 8 ) | ( ( value & 0x00FF00FFL ) << 8 );
}
}
#endif /* #ifndef WORDS_BIGENDIAN */
@ -260,21 +260,21 @@ void shsUpdate(SHS_INFO* shsInfo, uint8* buffer, int count)
{
/* Update bitcount */
if( ( shsInfo->countLo + ( ( uint32 ) count << 3 ) ) < shsInfo->countLo )
shsInfo->countHi++; /* Carry from low to high bitCount */
shsInfo->countHi++; /* Carry from low to high bitCount */
shsInfo->countLo += ( ( uint32 ) count << 3 );
shsInfo->countHi += ( ( uint32 ) count >> 29 );
/* Process data in SHS_BLOCKSIZE chunks */
while( count >= SHS_BLOCKSIZE )
{
memcpy( (char *) shsInfo->data, (char *) buffer, SHS_BLOCKSIZE );
{
memcpy( (char *) shsInfo->data, (char *) buffer, SHS_BLOCKSIZE );
#ifndef WORDS_BIGENDIAN
byteReverse( shsInfo->data, SHS_BLOCKSIZE );
byteReverse( shsInfo->data, SHS_BLOCKSIZE );
#endif /* #ifndef WORDS_BIGENDIAN */
shsTransform( shsInfo );
buffer += SHS_BLOCKSIZE;
count -= SHS_BLOCKSIZE;
}
shsTransform( shsInfo );
buffer += SHS_BLOCKSIZE;
count -= SHS_BLOCKSIZE;
}
/* Handle any remaining bytes of data. This should only happen once
on the final lot of data */
@ -295,20 +295,20 @@ void shsFinal(SHS_INFO *shsInfo)
/* Pad out to 56 mod 64 */
if( count > 56 )
{
/* Two lots of padding: Pad the first block to 64 bytes */
memset( ( char * ) shsInfo->data + count, 0, 64 - count );
{
/* Two lots of padding: Pad the first block to 64 bytes */
memset( ( char * ) shsInfo->data + count, 0, 64 - count );
#ifndef WORDS_BIGENDIAN
byteReverse( shsInfo->data, SHS_BLOCKSIZE );
byteReverse( shsInfo->data, SHS_BLOCKSIZE );
#endif /* #ifndef WORDS_BIGENDIAN */
shsTransform( shsInfo );
shsTransform( shsInfo );
/* Now fill the next block with 56 bytes */
memset( (char *) shsInfo->data, 0, 56 );
}
/* Now fill the next block with 56 bytes */
memset( (char *) shsInfo->data, 0, 56 );
}
else
/* Pad block to 56 bytes */
memset( ( char * ) shsInfo->data + count, 0, 56 - count );
/* Pad block to 56 bytes */
memset( ( char * ) shsInfo->data + count, 0, 56 - count );
#ifndef WORDS_BIGENDIAN
byteReverse( shsInfo->data, SHS_BLOCKSIZE );
#endif /* #ifndef WORDS_BIGENDIAN */
@ -350,14 +350,14 @@ void main()
shsUpdate( &shsInfo, ( uint8 * ) "abc", 3 );
shsFinal( &shsInfo );
if( shsInfo.digest[ 0 ] != 0x0164B8A9L ||
shsInfo.digest[ 1 ] != 0x14CD2A5EL ||
shsInfo.digest[ 2 ] != 0x74C4F7FFL ||
shsInfo.digest[ 3 ] != 0x082C4D97L ||
shsInfo.digest[ 4 ] != 0xF1EDF880L )
{
puts( "Error in SHS implementation" );
exit( -1 );
}
shsInfo.digest[ 1 ] != 0x14CD2A5EL ||
shsInfo.digest[ 2 ] != 0x74C4F7FFL ||
shsInfo.digest[ 3 ] != 0x082C4D97L ||
shsInfo.digest[ 4 ] != 0xF1EDF880L )
{
puts( "Error in SHS implementation" );
exit( -1 );
}
/* Now perform time trial, generating MD for 10MB of data. First,
initialize the test data */
@ -370,7 +370,7 @@ void main()
/* Calculate SHS message digest in TEST_BLOCK_SIZE byte blocks */
shsInit( &shsInfo );
for( i = TEST_BLOCKS; i > 0; i-- )
shsUpdate( &shsInfo, data, TEST_BLOCK_SIZE );
shsUpdate( &shsInfo, data, TEST_BLOCK_SIZE );
shsFinal( &shsInfo );
/* Get finish time and time difference */

View File

@ -46,10 +46,10 @@
/* The structure for storing SHS info */
typedef struct {
uint32 digest[ 5 ]; /* Message digest */
uint32 countLo, countHi; /* 64-bit bit count */
uint32 data[ 16 ]; /* SHS data buffer */
} SHS_INFO;
uint32 digest[ 5 ]; /* Message digest */
uint32 countLo, countHi; /* 64-bit bit count */
uint32 data[ 16 ]; /* SHS data buffer */
} SHS_INFO;
/* Whether the machine is little-endian or not */
@ -63,22 +63,22 @@ void shsFinal(SHS_INFO* shsInfo);
* formulation. Bruce Schneier described it thus in a posting to the
* Cypherpunks mailing list on June 21, 1994 (as told to us by Steve Bellovin):
*
* This is the fix to the Secure Hash Standard, NIST FIPS PUB 180:
* This is the fix to the Secure Hash Standard, NIST FIPS PUB 180:
*
* In Section 7 of FIPS 180 (page 9), the line which reads
* In Section 7 of FIPS 180 (page 9), the line which reads
*
* "b) For t=16 to 79 let Wt = Wt-3 XOR Wt-8 XOR Wt-14 XOR
* Wt-16."
* "b) For t=16 to 79 let Wt = Wt-3 XOR Wt-8 XOR Wt-14 XOR
* Wt-16."
*
* is to be replaced by
* is to be replaced by
*
* "b) For t=16 to 79 let Wt = S1(Wt-3 XOR Wt-8 XOR Wt-14 XOR
* Wt-16)."
* "b) For t=16 to 79 let Wt = S1(Wt-3 XOR Wt-8 XOR Wt-14 XOR
* Wt-16)."
*
* where S1 is a left circular shift by one bit as defined in
* Section 3 of FIPS 180 (page 6):
* where S1 is a left circular shift by one bit as defined in
* Section 3 of FIPS 180 (page 6):
*
* S1(X) = (X<<1) OR (X>>31).
* S1(X) = (X<<1) OR (X>>31).
*
*/

View File

@ -54,8 +54,8 @@
class iSerRefCountObj : public cRefCountObj, public iTypedSerializable
{
public:
// the creation function
typedef iSerRefCountObj* (*CreateFunc)(void);
// the creation function
typedef iSerRefCountObj* (*CreateFunc)(void);
protected:
virtual ~iSerRefCountObj();
@ -65,21 +65,21 @@ protected:
//////////////////////////////
// convenience macros
#define DECLARE_SERREFCOUNT() \
DECLARE_TYPED() \
public: \
static iSerRefCountObj* Create(); \
virtual int32 Version() const;
DECLARE_TYPED() \
public: \
static iSerRefCountObj* Create(); \
virtual int32 Version() const;
#define IMPLEMENT_SERREFCOUNT(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \
IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \
iSerRefCountObj* CLASS::Create() \
{ \
return new CLASS; \
} \
int32 CLASS::Version() const \
{ \
return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \
}
IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \
iSerRefCountObj* CLASS::Create() \
{ \
return new CLASS; \
} \
int32 CLASS::Version() const \
{ \
return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \
}
#endif

View File

@ -54,8 +54,8 @@ cSerRefCountTable::~cSerRefCountTable()
void cSerRefCountTable::Clear()
{
mIDToObjTbl.clear();
mObjToIdTbl.clear();
mIDToObjTbl.clear();
mObjToIdTbl.clear();
}
// find the table id for object. returns 0 if not in table.
@ -63,10 +63,10 @@ int cSerRefCountTable::Lookup(const iSerRefCountObj* pObj)
{
std::map<iSerRefCountObj*, int>::iterator itr;
// pay no attention to this cast :-)
itr = mObjToIdTbl.find(const_cast<iSerRefCountObj*>(pObj));
// pay no attention to this cast :-)
itr = mObjToIdTbl.find(const_cast<iSerRefCountObj*>(pObj));
return itr == mObjToIdTbl.end() ? NULL : itr->second;
return (itr == mObjToIdTbl.end()) ? 0 : itr->second;
}
// find object for specified id. returns NULL if not in table
@ -86,8 +86,8 @@ int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id)
{
if (Lookup(pObj) != 0)
{
// this should be a programming error, but we will throw just to be safe...
ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed object already in table.")));
// this should be a programming error, but we will throw just to be safe...
ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed object already in table.")));
}
if (id == 0)
{
@ -96,8 +96,8 @@ int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id)
}
else if (Lookup(id) != NULL)
{
// this should be a programming error, but we will throw just to be safe...
ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed ID already in table.")));
// this should be a programming error, but we will throw just to be safe...
ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed ID already in table.")));
}
mIDToObjTbl.insert( MapIDTObj::value_type(id, pObj));
@ -108,8 +108,8 @@ int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id)
int cSerRefCountTable::Add(const iSerRefCountObj* pObj, int id)
{
iSerRefCountObj* pNonConst = const_cast<iSerRefCountObj*>(pObj);
return Add(pNonConst, id);
iSerRefCountObj* pNonConst = const_cast<iSerRefCountObj*>(pObj);
return Add(pNonConst, id);
}
///////////////////////////////////////////////////////////////////////////////

View File

@ -54,17 +54,17 @@ public:
// Add an object to the table, optionally specifying an ID. Returns a
// unique ID for the object. ASSERTs and throws exception if object is
// already in table or the ID is already taken.
int Add( 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
// 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
// reading or writing and (maybe?) make this class a template class so that it can map
// to either const or non-const objects.
int Add( 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
// 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
// reading or writing and (maybe?) make this class a template class so that it can map
// to either const or non-const objects.
// clears out the table
void Clear();
// clears out the table
void Clear();
protected:
typedef std::map<int, iSerRefCountObj*> MapIDTObj;

View File

@ -88,7 +88,7 @@ public:
const byte* operator()( const wc16_string& s, int* const pcbKeyLen )
{
*pcbKeyLen = sizeof(WCHAR16) * s.length();
return (byte*)s.c_str();
return (byte*)s.c_str();
}
};
@ -97,7 +97,7 @@ class tss_hash_key_compare
public:
bool operator()( const wc16_string& lhs, const wc16_string& rhs )
{
return ( lhs.compare( rhs ) == 0 );
return ( lhs.compare( rhs ) == 0 );
}
};
@ -506,12 +506,12 @@ void cMBUCS2Cache::Add(mbchar_t* pMBchar, int mblen, dbchar_t ucs2)
static inline const byte* tss_hash_key_convert()( const TCHAR* psz, int* const pcbKeyLen )
{
*pcbKeyLen = sizeof(TCHAR) * _tcslen( psz );
return (byte*)psz;
return (byte*)psz;
}
static inline bool tss_hash_key_compare()( const TCHAR* lhs, const TCHAR* rhs )
{
return ( _tcscmp( lhs, rhs ) == 0 );
return ( _tcscmp( lhs, rhs ) == 0 );
}
cHashTable< dbchar_t*,

View File

@ -55,9 +55,9 @@ inline
void TestStringUtil()
{
#if USING_NTDBS_STUFF
cDebug db("Test std::char_traits<dbchar_t>");
cDebug db("Test std::char_traits<dbchar_t>");
db.TraceAlways("Entering...\n");
db.TraceAlways("Entering...\n");
tss::dbstring a;
tss::dbstring b;
@ -143,7 +143,7 @@ void TestStringUtil()
//std::string TstrToStr( const TSTRING& tstr );
//TSTRING StrToTstr( const std::string& str );
//TSTRING WstrToTstr( const wc16_string& src );
//wc16_string TstrToWstr( const TSTRING& tstr );
//wc16_string TstrToWstr( const TSTRING& tstr );
// test Null assignments
singleStr = cStringUtil::TstrToStr( tStrNull );

View File

@ -54,42 +54,42 @@ template<class TIME_FN, class TIME_TYPE>
class cTaskTimer
{
public:
cTaskTimer(const TSTRING& name) : mName(name), mTotalTime(0), mStartTime(0), mNumStarts(0) {}
~cTaskTimer();
cTaskTimer(const TSTRING& name) : mName(name), mTotalTime(0), mStartTime(0), mNumStarts(0) {}
~cTaskTimer();
void Start();
void Stop();
bool IsRunning() { return (mStartTime != 0); }
void Reset() { mNumStarts = mStartTime = mTotalTime = 0 }
int32 GetTotalTime() const;
int32 GetNumTimesStarted() const; // returns the number of times start() was called
const std::string& GetName() const;
void Start();
void Stop();
bool IsRunning() { return (mStartTime != 0); }
void Reset() { mNumStarts = mStartTime = mTotalTime = 0 }
int32 GetTotalTime() const;
int32 GetNumTimesStarted() const; // returns the number of times start() was called
const std::string& GetName() const;
private:
TSTRING mName;
int32 mTotalTime;
TIME_TYPE mStartTime;
int32 mNumStarts;
TSTRING mName;
int32 mTotalTime;
TIME_TYPE mStartTime;
int32 mNumStarts;
};
#if IS_UNIX
///////////////////////////////////////////////////////////////////////////////
// cUnixTimeFn -- Unix version, inserts proper function call and overloads
// operator()
// operator()
///////////////////////////////////////////////////////////////////////////////
#include <ctime>
class cUnixTimeFn
{
public:
typedef uint32 DataType;
typedef uint32 DataType;
uint32 operator()()
{
return time( &dummy_var );
}
uint32 operator()()
{
return time( &dummy_var );
}
private:
time_t dummy_var;
time_t dummy_var;
};
///////////////////////////////////////////////////////////////////////////////
@ -105,45 +105,45 @@ typedef cUnixTaskTimer cGenericTaskTimer;
//-----------------------------------------------------------------------------
template<class TIME_FN, class TIME_TYPE>
inline void cTaskTimer<TIME_FN, TIME_TYPE>::Start()
inline void cTaskTimer<TIME_FN, TIME_TYPE>::Start()
{
ASSERT(! IsRunning());
TIME_FN GetTime;
mStartTime = GetTime();
mNumStarts++;
ASSERT(! IsRunning());
TIME_FN GetTime;
mStartTime = GetTime();
mNumStarts++;
}
template<class TIME_FN, class TIME_TYPE>
inline void cTaskTimer<TIME_FN, TIME_TYPE>::Stop()
inline void cTaskTimer<TIME_FN, TIME_TYPE>::Stop()
{
ASSERT(IsRunning());
TIME_FN GetTime;
mTotalTime += ( GetTime() - mStartTime );
mStartTime = 0;
ASSERT(IsRunning());
TIME_FN GetTime;
mTotalTime += ( GetTime() - mStartTime );
mStartTime = 0;
}
template<class TIME_FN, class TIME_TYPE>
inline int32 cTaskTimer<TIME_FN, TIME_TYPE>::GetTotalTime() const
{
return mTotalTime;
return mTotalTime;
}
template<class TIME_FN, class TIME_TYPE>
inline const std::string& cTaskTimer<TIME_FN, TIME_TYPE>::GetName() const
{
return mName
return mName
}
template<class TIME_FN, class TIME_TYPE>
inline cTaskTimer<TIME_FN, TIME_TYPE>::~cTaskTimer()
{
// stop the timer if it is currently running
if(IsRunning())
Stop();
// stop the timer if it is currently running
if(IsRunning())
Stop();
// trace out the time contents...
cDebug d("cTaskTimer");
d.TraceDebug("----- Time to execute %s: %d (started %d times)\n", mName.c_str(), mTotalTime, mNumStarts);
// trace out the time contents...
cDebug d("cTaskTimer");
d.TraceDebug("----- Time to execute %s: %d (started %d times)\n", mName.c_str(), mTotalTime, mNumStarts);
}

View File

@ -114,12 +114,12 @@ typedef std::ifstream TIFSTREAM;
#define _tcsncmp strncmp
// other abstractions
#define TUNLINK unlink
#define TUNLINK unlink
// string representation
#if defined(_T)
// 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
#endif
#define _T(x) x

View File

@ -1,133 +0,0 @@
//
// The developer of the original code and/or files is Tripwire, Inc.
// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire,
// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights
// reserved.
//
// This program is free software. The contents of this file are subject
// to the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. You may redistribute it and/or modify it
// only in compliance with the GNU General Public License.
//
// This program is distributed in the hope that it will be useful.
// However, this program is distributed AS-IS WITHOUT ANY
// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// Nothing in the GNU General Public License or any other license to use
// the code or files shall permit you to use Tripwire's trademarks,
// service marks, or other intellectual property without Tripwire's
// prior written consent.
//
// If you have any questions, please contact Tripwire, Inc. at either
// info@tripwire.org or www.tripwire.org.
//
#include "stdcore.h"
#include <string>
#include <iostream>
#include <fstream>
#ifndef __DEBUG_H
#include "debug.h"
#endif
TSTRING test_wost(int, const TSTRING&);
void test_wist(const TSTRING&, cDebug& d);
void TestTCHAR()
{
cDebug d("TestTCHAR()");
d.TraceDetail("Entering...\n");
//Testing TCOUT:
TCOUT<< _T("Simple test of TSTRING (and TCOUT) :\n\n");
TCERR<< _T("This should show up on cerr");
TSTRING pString;
pString = _T("Hi Mom!");
d.TraceDetail("%s \n", pString.c_str() );
d.TraceDetail("Isn't this cool?\n\n");
//Begin fun tests of string streams:
TSTRINGSTREAM wst;
//can I declare it?
TSTRING str;
str = _T("Kiteman");
TSTRING test1 = _T("word");
d.TraceDetail("Testing TOSTRINGSTREAM with TSTRING:\n");
TOSTRINGSTREAM ost(_T("test up"));
ost<<test1;
d.TraceDetail("%s \n", ost.str() );
//if this gives output, then I'm really baffled...
//test gets overwritten, yielding "word up"
TSTRING output;
output = test_wost(3, str);
d.TraceDetail("%s \n", output.c_str());
//A true statement!
d.TraceDetail("Testing TISTRINGSTREAM with TSTRING:\n");
TSTRING send = _T("These should appear on seperate lines");
test_wist(send, d);
//Did they?
//Testing file streams
//explict constructors of 'TIFSTREAM' and "TOFSTREAM' take char*
const char* inputfile = "fun";
const char* outputfile = "mo'fun";
//Set up the input file.
TOFSTREAM out;
out.open(inputfile, std::ios_base::out);
out<<"Unicode is fun\n";
out.close();
TIFSTREAM from;
from.open(inputfile, std::ios_base::in);
if(!from)
d.TraceDetail("error opening input file\n");
TOFSTREAM to(outputfile, std::ios_base::trunc);
if(!to)
d.TraceDetail("error opening output file\n");
//Copy contents of input file to output file.
TCHAR ch;
while(from.get(ch))
to.put(ch);
if(!from.eof() || !to)
d.TraceDetail("something has gone terribly wrong...\n");
return;
}
TSTRING test_wost(int n, const TSTRING& inject)
{
TOSTRINGSTREAM wost(_T("Weird how this doesn't show up! "));
//It's getting overwritten, why?
wost<<_T("One out of every ")<<n<<_T(" children loves ")<<inject<<_T("!\n");
return wost.str();
}
void test_wist(const TSTRING& input, cDebug& d)
{
TISTRINGSTREAM wist(input);
TSTRING parse;
while(wist>>parse)
d.TraceDetail("%s \n", parse.c_str() );
}

View File

@ -44,7 +44,7 @@
//
bool TimeBombExploded()
{
struct tm time_struct;
struct tm time_struct;
/*
memset(&time_struct, 0, sizeof(time_struct));

View File

@ -52,7 +52,7 @@
// METHOD CODE
//=========================================================================
#define TIME_MAX 2147483647L // largest signed 32 bit number
#define TIME_MAX 2147483647L // largest signed 32 bit number
#ifdef __AROS__
#define tzset()

View File

@ -44,36 +44,36 @@ static void tw_psignal( int sig, const TCHAR* s );
tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc)
{
return signal(sig, pFunc);
return signal(sig, pFunc);
}
int tw_raise(int sig)
{
return raise(sig);
return raise(sig);
}
tw_sighandler_t tw_sigign(int sig)
{
return signal(sig, SIG_IGN);
return signal(sig, SIG_IGN);
}
//////////////////////////////////////////////////////////////////////
// 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 )
{
return signal( sig, util_SignalHandler );
return signal( sig, util_SignalHandler );
}
void util_SignalHandler( int sig )
{
//If we're on unix, let's print out a nice error message telling
//the user which signal we've recieved.
//If we're on unix, let's print out a nice error message telling
//the user which signal we've recieved.
#if IS_UNIX
tw_psignal( sig, (TSS_GetString( cCore, core::STR_SIGNAL).c_str() ) );
tw_psignal( sig, (TSS_GetString( cCore, core::STR_SIGNAL).c_str() ) );
#endif
exit( 8 );
exit( 8 );
}
#if IS_UNIX
@ -108,7 +108,7 @@ void tw_psignal(int sig, const TCHAR *str)
_T("Virtual Timer Expired"),
_T("Profiling Timer Expired"),
_T("Pollable Event"),
_T("Window Size Change"),
_T("Window Size Change"),
_T("Stopped (signal)"),
_T("Stopped (user)"),
_T("Continued"),

View File

@ -31,7 +31,7 @@
//
///////////////////////////////////////////////////////////////////////////////
// tw_signal.h -- a wrapper around signal(), needed because of linux
// build issues
// build issues
//
#ifndef __TW_SIGNAL_H
#define __TW_SIGNAL_H
@ -39,7 +39,7 @@
#include <signal.h>
#ifdef HAVE_SIGNUM_H
#include <signum.h> // the signal number constants
#include <signum.h> // the signal number constants
#endif
#ifdef HAVE_BITS_SIGNUM_H
#include <bits/signum.h>
@ -50,7 +50,7 @@ typedef void (*tw_sighandler_t)(int);
}
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)

View File

@ -172,7 +172,7 @@ public:
// Format( numT n, std::basic_string< CharT >& sBuf )
//-----------------------------------------------------------------------------
// EFFECTS: Does all actual formatting for FormatNumber methods
//
//
static
std::basic_string< CharT >&
Format( numT n, std::basic_string< CharT >& sBuf, bool fCStyleFormatting = false )
@ -255,8 +255,8 @@ TSTRING& cTWLocale::FormatTime( int64 t, TSTRING& strBuf )
{
util_FormatTime( ptm, strBuf );
}
else
{
else
{
strBuf = TSS_GetString( cCore, core::STR_UNKNOWN_TIME );
}
@ -311,7 +311,7 @@ TSTRING& util_FormatTimeC( struct tm* ptm, TSTRING& strBuf )
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 ),
#if IS_MSVC // MSVC uses proprietary '#'

View File

@ -38,7 +38,7 @@
enum Languages
{
LANG_USENGLISH = 1
LANG_USENGLISH = 1
};
#endif

View File

@ -44,23 +44,23 @@
class cType
{
public:
cType(const TCHAR* name);
const TCHAR* AsString() const;
bool operator==(const cType& rhs) const;
bool operator!=(const cType& rhs) const;
cType(const TCHAR* name);
const TCHAR* AsString() const;
bool operator==(const cType& rhs) const;
bool operator!=(const cType& rhs) const;
private:
TSTRING mString;
TSTRING mString;
};
class iTyped
{
public:
virtual const cType& GetType() const = 0;
// the type of an FCO; classes that implement this interface need to
// (a) declare a public static const cType member mType and
// (b) returning that object in their implementation of GetType()
// You can use the macros below to simplify the process
virtual const cType& GetType() const = 0;
// the type of an FCO; classes that implement this interface need to
// (a) declare a public static const cType member mType and
// (b) returning that object in their implementation of GetType()
// You can use the macros below to simplify the process
virtual ~iTyped() {}
};
@ -72,70 +72,70 @@ public:
public:\
static const cType mType;\
virtual const cType& GetType() const;
// put DECLARE_TYPED in the class definition
// put DECLARE_TYPED in the class definition
#define IMPLEMENT_TYPED(CLASS, STRING)\
const cType CLASS::mType(STRING);\
const cType CLASS::mType(STRING);\
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
// a convienent way to specify a class's type
// a convienent way to specify a class's type
///////////////////////////////////////////////
// iTyped Example
///////////////////////////////////////////////
/*
(foo.h)
class cFoo : public iTyped
{
public:
DECLARE_TYPED()
}
(foo.h)
class cFoo : public iTyped
{
public:
DECLARE_TYPED()
}
(foo.cpp)
DECLARE_TYPED(cFoo, "Foo");
(foo.cpp)
DECLARE_TYPED(cFoo, "Foo");
(main.cpp)
int main()
{
iTyped* pi = Bar(); // returned a cFoo
cout << "Encountered class " << pi->GetType().AsString() << endl;
// prints "Encountered class Foo"
if(pi->GetType() == CLASS_TYPE(cFoo))
{
cFoo* pFoo = static_cast<cFoo*>(pi);
// cast is always safe
}
}
(main.cpp)
int main()
{
iTyped* pi = Bar(); // returned a cFoo
cout << "Encountered class " << pi->GetType().AsString() << endl;
// prints "Encountered class Foo"
if(pi->GetType() == CLASS_TYPE(cFoo))
{
cFoo* pFoo = static_cast<cFoo*>(pi);
// cast is always safe
}
}
*/
///////////////////////////////////////////////////////////////////////////////
// inline implementation
///////////////////////////////////////////////////////////////////////////////
inline cType::cType(const TCHAR* name) :
mString(name)
mString(name)
{
ASSERT(!mString.empty());
ASSERT(!mString.empty());
}
inline const TCHAR* cType::AsString() const
inline const TCHAR* cType::AsString() const
{
return mString.c_str();
return mString.c_str();
}
inline bool cType::operator==(const cType& rhs) const
{
return (this == &rhs);
return (this == &rhs);
}
inline bool cType::operator!=(const cType& rhs) const
{
return (this != &rhs);
return (this != &rhs);
}

View File

@ -40,38 +40,38 @@
// standard TSS types
//-----------------------------------------------------------------------------
typedef unsigned char byte ; // platform-independent
typedef unsigned char byte ; // platform-independent
typedef signed char int8 ;
typedef short int16 ;
typedef float float32 ;
typedef double float64 ;
typedef unsigned char uint8 ;
typedef unsigned short uint16 ;
typedef signed char int8 ;
typedef short int16 ;
typedef float float32 ;
typedef double float64 ;
typedef unsigned char uint8 ;
typedef unsigned short uint16 ;
#if SIZEOF_INT == 4
typedef int int32 ;
typedef unsigned int uint32 ;
typedef int int32 ;
typedef unsigned int uint32 ;
#elif SIZEOF_LONG == 4
typedef long int32 ;
typedef unsigned long uint32 ;
typedef long int32 ;
typedef unsigned long uint32 ;
#else
# error "I don't seem to have a 32-bit integer type on this system."
#endif
#if SIZEOF_LONG == 8
typedef long int64 ;
typedef unsigned long uint64 ;
typedef long int64 ;
typedef unsigned long uint64 ;
#elif SIZEOF_LONG_LONG == 8
typedef long long int64 ;
typedef unsigned long long uint64 ;
typedef long long int64 ;
typedef unsigned long long uint64 ;
#else
# error "I don't seem to have a 64-bit integer type on this system."
#endif
// other Win32 definitions
//typedef uint16 UINT;
//typedef uint32 DWORD;
//typedef uint16 UINT;
//typedef uint32 DWORD;
//-----------------------------------------------------------------------------
// Limits -- should be platform independent, right? ( assumes 2's complement numbers )

View File

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

View File

@ -43,12 +43,12 @@
TSS_BEGIN_EXCEPTION( eUnix, eError )
eUnix( const TCHAR* functionName, const TCHAR* objectName, bool displayErrorNumber = true );
// 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
// that contains all of the above information plus whatever errno returns if the dusplayErrorNumber
// parameter is true.
eUnix( const TCHAR* functionName, const TCHAR* objectName, bool displayErrorNumber = true );
// 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
// that contains all of the above information plus whatever errno returns if the dusplayErrorNumber
// parameter is true.
TSS_END_EXCEPTION()

View File

@ -32,7 +32,7 @@
//////////////////////////////////////////////////////////////////
// unixfsservices.cpp
//
// Implements cUnixFSServices class in unixfsservices.h
// Implements cUnixFSServices class in unixfsservices.h
//
#include "core/stdcore.h"
@ -143,18 +143,18 @@ cUnixFSServices::~cUnixFSServices()
///////////////////////////////////////////////////////////////////////////////
// GetErrString
///////////////////////////////////////////////////////////////////////////////
TSTRING cUnixFSServices::GetErrString() const
TSTRING cUnixFSServices::GetErrString() const
{
TSTRING ret;
char* pErrorStr = strerror(errno);
TSTRING ret;
char* pErrorStr = strerror(errno);
#ifdef _UNICODE
wchar_t pBuf[1024];
mbstowcs(pBuf, pErrorStr, 1024);
ret = pBuf;
wchar_t pBuf[1024];
mbstowcs(pBuf, pErrorStr, 1024);
ret = pBuf;
#else
ret = pErrorStr;
ret = pErrorStr;
#endif
return ret;
return ret;
}
@ -186,71 +186,71 @@ void cUnixFSServices::ReadDir(const TSTRING& strFilename, std::vector<TSTRING> &
#else
void cUnixFSServices::ReadDir(const TSTRING& strFilenameC, std::vector<TSTRING>& v, bool bFullPaths) const throw(eFSServices)
{
TSTRING strFilename = cArosPath::AsNative(strFilenameC);
TSTRING strFilename = cArosPath::AsNative(strFilenameC);
#endif
//Get all the filenames
DIR* dp;
dp = opendir( strFilename.c_str() );
//Get all the filenames
DIR* dp;
dp = opendir( strFilename.c_str() );
if (dp == NULL)
{
throw eFSServicesGeneric( strFilename, iFSServices::GetInstance()->GetErrString() );
return;
}
struct dirent* d;
if (dp == NULL)
{
throw eFSServicesGeneric( strFilename, iFSServices::GetInstance()->GetErrString() );
return;
}
struct dirent* d;
while ((d = readdir(dp)) != NULL)
{
if ((strcmp(d->d_name, _T(".")) != 0) && (strcmp(d->d_name, _T("..")) != 0))
{
if( bFullPaths )
{
//Create the full pathname
TSTRING strNewName = strFilename;
while ((d = readdir(dp)) != NULL)
{
if ((strcmp(d->d_name, _T(".")) != 0) && (strcmp(d->d_name, _T("..")) != 0))
{
if( bFullPaths )
{
//Create the full pathname
TSTRING strNewName = strFilename;
// get full path of dir entry
util_TrailingSep( strNewName, true );
strNewName += d->d_name;
// get full path of dir entry
util_TrailingSep( strNewName, true );
strNewName += d->d_name;
// save full path name
v.push_back( strNewName );
}
else
v.push_back( d->d_name );
}
}
// save full path name
v.push_back( strNewName );
}
else
v.push_back( d->d_name );
}
}
//Close the directory
closedir( dp );
//Close the directory
closedir( dp );
}
/* needs to and with S_IFMT, check EQUALITY with S_*, and return more types
cFSStatArgs::FileType cUnixFSServices::GetFileType(const cFCOName &filename) throw(eFSServices)
{
cFSStatArgs stat;
Stat(filename, stat);
return stat.mFileType;
cFSStatArgs stat;
Stat(filename, stat);
return stat.mFileType;
}
*/
void cUnixFSServices::GetCurrentDir( TSTRING& strCurDir ) const throw(eFSServices)
{
TCHAR pathname[iFSServices::TW_MAX_PATH];
pathname[0] = '\0';
TCHAR* ret = getcwd(pathname, sizeof(TCHAR)*iFSServices::TW_MAX_PATH);
TCHAR pathname[iFSServices::TW_MAX_PATH];
pathname[0] = '\0';
TCHAR* ret = getcwd(pathname, sizeof(TCHAR)*iFSServices::TW_MAX_PATH);
if (ret == NULL)
throw eFSServicesGeneric( strCurDir, iFSServices::GetInstance()->GetErrString() );
if (ret == NULL)
throw eFSServicesGeneric( strCurDir, iFSServices::GetInstance()->GetErrString() );
strCurDir = pathname;
}
void cUnixFSServices::ChangeDir( const TSTRING& strDir ) const throw(eFSServices)
{
if( chdir( strDir.c_str() ) < 0 )
throw eFSServicesGeneric( strDir, iFSServices::GetInstance()->GetErrString() );
if( chdir( strDir.c_str() ) < 0 )
throw eFSServicesGeneric( strDir, iFSServices::GetInstance()->GetErrString() );
}
@ -294,7 +294,7 @@ TSTRING& cUnixFSServices::MakeTempFilename( TSTRING& strName ) const throw(eFSSe
wchar_t wcsbuf[1024];
mbstowcs( wcsbuf, pchTempFileName, strlen( pchTempFileName ) + 1 ));
strName = wcsbuf;
#else
#else
strName = pchTempFileName;
#endif
@ -303,25 +303,25 @@ TSTRING& cUnixFSServices::MakeTempFilename( TSTRING& strName ) const throw(eFSSe
// So I'll always attempt to delete it -bam
FileDelete( strName );
return( strName );
return( strName );
}
void cUnixFSServices::Mkdir( const TSTRING& strName ) const throw ( eFSServices )
{
if( 0 != _tmkdir( strName.c_str(), 0777 ) )
if( 0 != _tmkdir( strName.c_str(), 0777 ) )
{
// if mkdir failed because the dir existed, that's OK
if( errno != EEXIST )
throw eFSServicesGeneric( strName, iFSServices::GetInstance()->GetErrString() );
throw eFSServicesGeneric( strName, iFSServices::GetInstance()->GetErrString() );
}
}
}
bool cUnixFSServices::Rmdir( const TSTRING& strName ) const
{
if( 0 == rmdir( strName.c_str() ) )
return true;
if( 0 == rmdir( strName.c_str() ) )
return true;
return false;
return false;
}
void cUnixFSServices::GetTempDirName( TSTRING& strName ) const throw(eFSServices)
@ -341,19 +341,19 @@ void cUnixFSServices::Stat( const TSTRING& strName, cFSStatArgs &stat ) const th
#else
void cUnixFSServices::Stat( const TSTRING& strNameC, cFSStatArgs& stat) const throw(eFSServices)
{
TSTRING strName = cArosPath::AsNative(strNameC);
TSTRING strName = cArosPath::AsNative(strNameC);
#endif
//local variable for obtaining info on file.
struct stat statbuf;
//local variable for obtaining info on file.
struct stat statbuf;
int ret;
ret = lstat( strName.c_str(), &statbuf );
int ret;
ret = lstat( strName.c_str(), &statbuf );
cDebug d( "cUnixFSServices::Stat" );
d.TraceDetail( "Executing on file %s (result=%d)\n", strName.c_str(), ret );
cDebug d( "cUnixFSServices::Stat" );
d.TraceDetail( "Executing on file %s (result=%d)\n", strName.c_str(), ret );
if( ret < 0 )
throw eFSServicesGeneric( strName, iFSServices::GetInstance()->GetErrString() );
if( ret < 0 )
throw eFSServicesGeneric( strName, iFSServices::GetInstance()->GetErrString() );
// new stuff 7/17/99 - BAM
// if the file is not a device set rdev to zero by hand (most OSs will
@ -365,46 +365,46 @@ void cUnixFSServices::Stat( const TSTRING& strNameC, cFSStatArgs& stat) const th
util_ZeroMemory( statbuf.st_rdev );
}
//copy information returned by lstat call into the structure passed in
stat.gid = statbuf.st_gid;
stat.atime = statbuf.st_atime;
stat.ctime = statbuf.st_ctime;
stat.mtime = statbuf.st_mtime;
stat.dev = statbuf.st_dev;
stat.rdev = statbuf.st_rdev;
stat.ino = statbuf.st_ino;
stat.mode = statbuf.st_mode;
stat.nlink = statbuf.st_nlink;
stat.size = statbuf.st_size;
stat.uid = statbuf.st_uid;
//copy information returned by lstat call into the structure passed in
stat.gid = statbuf.st_gid;
stat.atime = statbuf.st_atime;
stat.ctime = statbuf.st_ctime;
stat.mtime = statbuf.st_mtime;
stat.dev = statbuf.st_dev;
stat.rdev = statbuf.st_rdev;
stat.ino = statbuf.st_ino;
stat.mode = statbuf.st_mode;
stat.nlink = statbuf.st_nlink;
stat.size = statbuf.st_size;
stat.uid = statbuf.st_uid;
stat.blksize = statbuf.st_blksize;
stat.blocks = statbuf.st_blocks;
// set the file type
if(S_ISREG(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_FILE;
else if(S_ISDIR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_DIR;
else if(S_ISLNK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_SYMLINK;
else if(S_ISBLK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_BLOCKDEV;
else if(S_ISCHR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_CHARDEV;
else if(S_ISFIFO(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_FIFO;
else if(S_ISSOCK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_SOCK;
// set the file type
if(S_ISREG(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_FILE;
else if(S_ISDIR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_DIR;
else if(S_ISLNK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_SYMLINK;
else if(S_ISBLK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_BLOCKDEV;
else if(S_ISCHR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_CHARDEV;
else if(S_ISFIFO(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_FIFO;
else if(S_ISSOCK(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_SOCK;
#ifdef S_IFDOOR
else if(S_ISDOOR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_DOOR;
else if(S_ISDOOR(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_DOOR;
#endif
#ifdef S_IFPORT
else if(S_ISPORT(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_PORT;
else if(S_ISPORT(statbuf.st_mode)) stat.mFileType = cFSStatArgs::TY_PORT;
#endif
else stat.mFileType = cFSStatArgs::TY_INVALID;
else stat.mFileType = cFSStatArgs::TY_INVALID;
}
void cUnixFSServices::GetMachineName( TSTRING& strName ) const throw( eFSServices )
{
struct utsname namebuf;
if( uname( &namebuf ) == -1 )
throw eFSServicesGeneric( strName );
else
strName = namebuf.nodename;
struct utsname namebuf;
if( uname( &namebuf ) == -1 )
throw eFSServicesGeneric( strName );
else
strName = namebuf.nodename;
}
void cUnixFSServices::GetMachineNameFullyQualified( TSTRING& strName ) const
@ -455,7 +455,7 @@ bool cUnixFSServices::GetCurrentUserName( TSTRING& strName ) const
fSuccess = true;
}
else
strName = _T("");
strName = _T("");
return( fSuccess );
}
@ -506,17 +506,17 @@ bool cUnixFSServices::GetIPAddress( uint32& uiIPAddress )
bool cUnixFSServices::IsCaseSensitive() const
{
return true;
return true;
}
bool cUnixFSServices::GetOwnerForFile( const TSTRING& tstrFilename, TSTRING& tstrUser ) const
{
bool fSuccess = true;
struct stat statbuf;
struct stat statbuf;
int ret = lstat(tstrFilename.c_str(), &statbuf);
if(ret < 0)
int ret = lstat(tstrFilename.c_str(), &statbuf);
if(ret < 0)
{
fSuccess = false;
}
@ -525,11 +525,11 @@ bool cUnixFSServices::GetOwnerForFile( const TSTRING& tstrFilename, TSTRING& tst
{
struct passwd* pp = getpwuid( statbuf.st_uid );
//ASSERT( pp );
// We shouldn't assert this, because it might be the case that a file
// is associated with some old user that no longer exists... we should
// not fail this case. Instead, the method will just return false per
// the test below.
if( pp == NULL )
// We shouldn't assert this, because it might be the case that a file
// is associated with some old user that no longer exists... we should
// not fail this case. Instead, the method will just return false per
// the test below.
if( pp == NULL )
{
fSuccess = false;
}
@ -545,10 +545,10 @@ bool cUnixFSServices::GetOwnerForFile( const TSTRING& tstrFilename, TSTRING& tst
bool cUnixFSServices::GetGroupForFile( const TSTRING& tstrFilename, TSTRING& tstrGroup ) const
{
bool fSuccess = true;
struct stat statbuf;
struct stat statbuf;
int ret = lstat(tstrFilename.c_str(), &statbuf);
if(ret < 0)
int ret = lstat(tstrFilename.c_str(), &statbuf);
if(ret < 0)
{
fSuccess = false;
}
@ -558,21 +558,21 @@ bool cUnixFSServices::GetGroupForFile( const TSTRING& tstrFilename, TSTRING& tst
struct group* pg = getgrgid( statbuf.st_gid );
//ASSERT( pg ); this assert stops everything in debug mode if we can't lookup a groupid
if( pg == NULL )
if( pg == NULL )
{
fSuccess = false;
tstrGroup = TSS_GetString(cCore, core::STR_UNKNOWN);
}
else
tstrGroup = pg->gr_name;
}
}
return( fSuccess );
}
////////////////////////////////////////////////////////////////////////
// Function name : cUnixFSServices::ConvertModeToString
// Description : takes a TSTRING and fills it with an "ls -l" representation
// Function name : cUnixFSServices::ConvertModeToString
// Description : takes a TSTRING and fills it with an "ls -l" representation
// of the object's permission bits ( e.g. "drwxr-x--x" ).
//
// Returns : void -- no errors are reported
@ -583,95 +583,95 @@ bool cUnixFSServices::GetGroupForFile( const TSTRING& tstrFilename, TSTRING& tst
void cUnixFSServices::ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) const
{
TCHAR szPerm[11]; //10 permission bits plus the NULL
_tcscpy( szPerm, _T("----------") );
_tcscpy( szPerm, _T("----------") );
ASSERT( sizeof(unsigned short) <= sizeof(uint32) );
// We do this in case an "unsigned short" is ever larger than the
// value we are switching on, since the size of the mode parameter
// will be unsigned short (whatever that means, for the given platform...)
ASSERT( sizeof(unsigned short) <= sizeof(uint32) );
// We do this in case an "unsigned short" is ever larger than the
// value we are switching on, since the size of the mode parameter
// will be unsigned short (whatever that means, for the given platform...)
// check file type
switch ((uint32)perm & S_IFMT) //some versions of Unix don't like to switch on
//64 bit values.
switch ((uint32)perm & S_IFMT) //some versions of Unix don't like to switch on
//64 bit values.
{
case S_IFDIR:
szPerm[0] = _T('d');
break;
case S_IFCHR:
szPerm[0] = _T('c');
break;
case S_IFBLK:
szPerm[0] = _T('b');
break;
case S_IFIFO:
szPerm[0] = _T('p');
break;
case S_IFLNK:
szPerm[0] = _T('l');
break;
case S_IFDIR:
szPerm[0] = _T('d');
break;
case S_IFCHR:
szPerm[0] = _T('c');
break;
case S_IFBLK:
szPerm[0] = _T('b');
break;
case S_IFIFO:
szPerm[0] = _T('p');
break;
case S_IFLNK:
szPerm[0] = _T('l');
break;
#ifdef S_IFDOOR
case S_IFDOOR:
szPerm[0] = _T('D');
break;
case S_IFDOOR:
szPerm[0] = _T('D');
break;
#endif
#ifdef S_IFPORT
case S_IFPORT:
szPerm[0] = _T('P');
break;
case S_IFPORT:
szPerm[0] = _T('P');
break;
#endif
break;
}
}
// check owner read and write
if (perm & S_IRUSR)
szPerm[1] = _T('r');
if (perm & S_IWUSR)
szPerm[2] = _T('w');
if (perm & S_IRUSR)
szPerm[1] = _T('r');
if (perm & S_IWUSR)
szPerm[2] = _T('w');
// check owner execute
if (perm & S_ISUID && perm & S_IXUSR)
szPerm[3] = _T('s');
else if (perm & S_IXUSR)
szPerm[3] = _T('x');
else if (perm & S_ISUID)
szPerm[3] = _T('S');
if (perm & S_ISUID && perm & S_IXUSR)
szPerm[3] = _T('s');
else if (perm & S_IXUSR)
szPerm[3] = _T('x');
else if (perm & S_ISUID)
szPerm[3] = _T('S');
// check group read and write
if (perm & S_IRGRP)
szPerm[4] = _T('r');
if (perm & S_IWGRP)
szPerm[5] = _T('w');
if (perm & S_IRGRP)
szPerm[4] = _T('r');
if (perm & S_IWGRP)
szPerm[5] = _T('w');
// check group execute
if (perm & S_ISGID && perm & S_IXGRP)
szPerm[6] = _T('s');
else if (perm & S_IXGRP)
szPerm[6] = _T('x');
else if (perm & S_ISGID)
szPerm[6] = _T('l');
if (perm & S_ISGID && perm & S_IXGRP)
szPerm[6] = _T('s');
else if (perm & S_IXGRP)
szPerm[6] = _T('x');
else if (perm & S_ISGID)
szPerm[6] = _T('l');
// check other read and write
if (perm & S_IROTH)
szPerm[7] = _T('r');
if (perm & S_IWOTH)
szPerm[8] = _T('w');
if (perm & S_IROTH)
szPerm[7] = _T('r');
if (perm & S_IWOTH)
szPerm[8] = _T('w');
// check other execute
if (perm & S_ISVTX && perm & S_IXOTH)
szPerm[9] = _T('t');
else if (perm & S_IXOTH)
szPerm[9] = _T('x');
else if (perm & S_ISVTX)
szPerm[9] = _T('T');
if (perm & S_ISVTX && perm & S_IXOTH)
szPerm[9] = _T('t');
else if (perm & S_IXOTH)
szPerm[9] = _T('x');
else if (perm & S_ISVTX)
szPerm[9] = _T('T');
tstrPerm = szPerm;
return;
return;
}
////////////////////////////////////////////////////////////////////////
// Function name : cUnixFSServices::Rename
// Description : Rename a file. Overwrites newname if it exists.and overwrite is true
// Function name : cUnixFSServices::Rename
// Description : Rename a file. Overwrites newname if it exists.and overwrite is true
//
// Returns : false if failure, true on success
bool cUnixFSServices::Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool overwrite) const
@ -728,16 +728,16 @@ bool cUnixFSServices::GetExecutableFilename( TSTRING& strFullPath, const TSTRING
///////////////////////////////////////////////////////////////////////////////
// Function name : cUnixFSServices::FullPath
// Description :
// Function name : cUnixFSServices::FullPath
// Description :
//
// Return type : bool
// Return type : bool
// Argument : TSTRING& strFullPath
// Argument : const TSTRING& strRelPathC
// Argument : const TSTRING& pathRelFromC
//
// TODO -- is throwing an exception the more appropriate alternative to returning
// a bool? I think it is ... mdb
// a bool? I think it is ... mdb
///////////////////////////////////////////////////////////////////////////////
bool cUnixFSServices::FullPath( TSTRING& strFullPath, const TSTRING& strRelPathC, const TSTRING& pathRelFromC ) const
{
@ -755,7 +755,7 @@ bool cUnixFSServices::FullPath( TSTRING& strFullPath, const TSTRING& strRelPathC
//
if( strRelPath[0] == TW_SLASH ) // if is absolute path
{
{
if( IsRoot( strRelPath ) ) // if it's root, don't monkey with it, just return it.
{
strFullPath = strRelPath;
@ -763,26 +763,26 @@ bool cUnixFSServices::FullPath( TSTRING& strFullPath, const TSTRING& strRelPathC
}
else
{
strFullPath = _T(""); // push root, then add path elements from strRelPathC
strFullPath = _T(""); // push root, then add path elements from strRelPathC
// one by one (in while loop below)
}
}
}
else // is a relative path, so check pathRelFromC
{
if( pathRelFromC.empty() ) // if we're relative to CWD...
{
//
// get the current working directory
//
try
{
GetCurrentDir( strFullPath );
//
// get the current working directory
//
try
{
GetCurrentDir( strFullPath );
util_TrailingSep( strFullPath, false );
}
catch( eFSServices& )
{
return false;
}
}
catch( eFSServices& )
{
return false;
}
}
else // we're relative to a given dir
{
@ -850,8 +850,8 @@ int cUnixFSServices::CreateLockedTemporaryFile( const TCHAR* szFilename, int per
O_CREAT | O_EXCL; // only create a new file -- error if it exists already
// create file
int fh = _topen( szFilename, oflags, 0666 );
if( fh >= 0 )
int fh = _topen( szFilename, oflags, 0666 );
if( fh >= 0 )
{
// file was created. Now unlink it
if( 0 != unlink( szFilename ) )
@ -873,10 +873,10 @@ void cUnixFSServices::Sleep( int nSeconds ) const
////////////////////////////////////////////////////////////////////////////////
// Function name : IsRoot
// Description : A root path is all '/'s
// Function name : IsRoot
// Description : A root path is all '/'s
//
// Return type : bool
// Return type : bool
// Argument : const TSTRING& strPath
///////////////////////////////////////////////////////////////////////////////
bool cUnixFSServices::IsRoot( const TSTRING& strPath ) const
@ -904,12 +904,12 @@ bool cUnixFSServices::IsRoot( const TSTRING& strPath ) const
///////////////////////////////////////////////////////////////////////////////
// Function name : util_PathFind
// Description :
// Function name : util_PathFind
// Description :
// takes single-element executible filename and looks in path env var for it
// assumes path is colon-delimited string of directories.
//
// Return type : bool
// Return type : bool
// Argument : TSTRING& strFullPath
// Argument : const TSTRING& strFilename
///////////////////////////////////////////////////////////////////////////////
@ -989,11 +989,11 @@ bool util_PathFind( TSTRING& strFullPath, const TSTRING& strFilename )
///////////////////////////////////////////////////////////////////////////////
// Function name : util_FileIsExecutable
// Description : file ( or file a link points to ) must be a regular
// Function name : util_FileIsExecutable
// Description : file ( or file a link points to ) must be a regular
// file and executable by someone
//
// Return type : bool
// Return type : bool
// Argument : const TSTRING& strFile
///////////////////////////////////////////////////////////////////////////////
bool util_FileIsExecutable( const TSTRING& strFile )
@ -1002,7 +1002,7 @@ bool util_FileIsExecutable( const TSTRING& strFile )
return false;
struct stat s;
if( stat( strFile.c_str(), &s ) < 0 ) // this call handles links
if( stat( strFile.c_str(), &s ) < 0 ) // this call handles links
return false;
return( S_ISREG( s.st_mode ) && ( s.st_mode & ( S_IXUSR | S_IXGRP | S_IXOTH ) ) ); // can someone execute it?
@ -1010,13 +1010,13 @@ bool util_FileIsExecutable( const TSTRING& strFile )
////////////////////////////////////////////////////////////////////////////////
// Function name : util_RemoveDuplicateSeps
// Description :
// Function name : util_RemoveDuplicateSeps
// Description :
// takes all adjacent slashes and replaces them with a single slash
// ///root//foo -> /root/foo
// rel//foo/// -> rel/foo/
//
// Return type : void
// Return type : void
// Argument : TSTRING& strPath
///////////////////////////////////////////////////////////////////////////////
void util_RemoveDuplicateSeps( TSTRING& strPath )
@ -1051,15 +1051,15 @@ void util_RemoveDuplicateSeps( TSTRING& strPath )
//////////////////////////////////////////////////////////////////////////////////
// Function name : util_RemoveLastPathElement
// Description :
// Function name : util_RemoveLastPathElement
// Description :
// effectively pops off a path element from the end, except for the root dir, where it does nothing
// it removes any slashes before and after the element
// ///root//foo/ -> leaves "///root" ("foo" is strElem)
// ///root -> leaves "" ("root" is strElem)
// // -> leaves "" ("" is strElem)
//
// Return type : void
// Return type : void
// Argument : TSTRING& strPath
// Argument : TSTRING& strElem
/////////////////////////////////////////////////////////////////////////////////
@ -1091,8 +1091,8 @@ void util_RemoveLastPathElement( TSTRING& strPath, TSTRING& strElem )
////////////////////////////////////////////////////////////////////////////////////
// Function name : util_GetNextPathElement
// Description :
// Function name : util_GetNextPathElement
// Description :
// starting from the left side of the path string, returns the index'th path element
// returns true if the element exists, false if there aren't <index + 1> many elements
//
@ -1101,7 +1101,7 @@ void util_RemoveLastPathElement( TSTRING& strPath, TSTRING& strElem )
// 2rd element of ABC/DEF/GH -> GH
// 1st element of //ABC/DEF/GH -> DEF
//
// Return type : bool : got path element? ( i.e. was there index path elements? )
// Return type : bool : got path element? ( i.e. was there index path elements? )
// Argument : const TSTRING& strPathC
// Argument : TSTRING& strElem
// Argument : int index
@ -1146,10 +1146,10 @@ bool util_GetNextPathElement( const TSTRING& strPathC, TSTRING& strElem, int ind
}
/////////////////////////////////////////////////////////////////////////
// Function name : util_TrailingSep
// Description : ensure that a path ( fLeaveSep ? "has" : "does not have" ) a trailing slash
// Function name : util_TrailingSep
// Description : ensure that a path ( fLeaveSep ? "has" : "does not have" ) a trailing slash
//
// Return type : bool : was there a trailing slash?
// Return type : bool : was there a trailing slash?
// Argument : TSTRING& str
// Argument : bool fLeaveSep
/////////////////////////////////////////////////////////////////////////////////
@ -1179,10 +1179,10 @@ bool util_TrailingSep( TSTRING& str, bool fLeaveSep )
}
/////////////////////////////////////////////////////////////////////////
// Function name : util_RemoveTrailingSeps
// Description : removes all trailing separators
// Function name : util_RemoveTrailingSeps
// Description : removes all trailing separators
//
// Return type : void
// Return type : void
// Argument : TSTRING& str
/////////////////////////////////////////////////////////////////////////////////
void util_RemoveTrailingSeps( TSTRING& str )

View File

@ -1,208 +0,0 @@
//
// The developer of the original code and/or files is Tripwire, Inc.
// Portions created by Tripwire, Inc. are copyright (C) 2000 Tripwire,
// Inc. Tripwire is a registered trademark of Tripwire, Inc. All rights
// reserved.
//
// This program is free software. The contents of this file are subject
// to the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version. You may redistribute it and/or modify it
// only in compliance with the GNU General Public License.
//
// This program is distributed in the hope that it will be useful.
// However, this program is distributed AS-IS WITHOUT ANY
// WARRANTY; INCLUDING THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
// FOR A PARTICULAR PURPOSE. Please see the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
// Nothing in the GNU General Public License or any other license to use
// the code or files shall permit you to use Tripwire's trademarks,
// service marks, or other intellectual property without Tripwire's
// prior written consent.
//
// If you have any questions, please contact Tripwire, Inc. at either
// info@tripwire.org or www.tripwire.org.
//
// unixfsservices_t.cpp: Tests cUnixFSServices
//#include <fcntl.h>
#include "core/stdcore.h"
#include "unixfsservices.h"
#include <iostream>
#include "core/archive.h"
#include "fco/fconame.h"
#if IS_UNIX
#ifndef __TEST_H
#include "test/test.h"
#endif
using namespace std;
//Tests the functions that are currently implemented in win32fsservices.
void TestUnixFSServices()
{
cDebug d("TestUnixFSServices");
// d.RemoveOutTarget(cDebug::OUT_STDOUT);
try
{
iFSServices* pFSServices = iFSServices::GetInstance();
// working primarily with the temp dir.
cFCOName name(_T("/tmp")); // dies here
// Check to make sure /tmp is a dir
//TEST(pFSServices->GetFileType(name) == cFSStatArgs::TY_DIR);
// get directory contents (test readdir)
std::vector <TSTRING> v;
pFSServices->ReadDir(name.AsString(), v);
{
d.TraceDebug("name: %d entries\n", v.size());
std::vector <TSTRING>::iterator p;
int n = 0;
for (p = v.begin(); p != v.end(); p++) {
d.TraceDetail(" %s\n", p->c_str());
n++;
}
TEST(n == v.size());
}
//Test the Stat method
cFSStatArgs stat;
//TO DO: use archive to create this file
TSTRING testfile = "/tmp/tmp.tmp";
cFileArchive filearch;
filearch.OpenReadWrite(testfile.c_str());
filearch.Seek(0, cBidirArchive::BEGINNING);
filearch.WriteString(_T("This is a test"));
filearch.Close();
pFSServices->Stat(testfile, stat);
//print out the information returned by Stat
d.TraceDetail("Information returned by Stat: \n");
d.TraceDetail("Group ID : %-5d \n", stat.gid);
//d.TraceDetail("Last access time: %d \n", stat.atime);
d.TraceDetail("Last inode change: %d \n", stat.ctime);
d.TraceDetail("Last modified: %d \n", stat.mtime);
d.TraceDetail("Major/minor device nums: %d \n", stat.dev);
d.TraceDetail("Inode # of file : %d \n", stat.ino);
d.TraceDetail("Mode bits: %d \n", stat.mode);
d.TraceDetail("Num links: %d \n", stat.nlink);
d.TraceDetail("Major/minor dev if special: %d \n", stat.rdev);
d.TraceDetail("File size: %d \n", stat.size);
d.TraceDetail("User ID: %d \n", stat.uid);
//Test GetCurrentDir:
TSTRING currpath;
pFSServices->GetCurrentDir(currpath);
d.TraceDetail("GetCurrentDir returned %s\n", currpath.c_str());
//TEST(currpath == _T("~"));
//they should both be ~!!
//Test MakeTempFilename
TSTRING _template(_T("twtempXXXXXX"));
pFSServices->MakeTempFilename(_template);
d.TraceDetail("Testing MakeTempFilename: \n");
d.TraceDetail("%s \n", _template.c_str() );
//Test ChangeDir
d.TraceDetail("Testing ChangeDir: (should be /usr)\n");
TSTRING newdir(_T("/usr"));
pFSServices->ChangeDir(newdir);
pFSServices->GetCurrentDir(currpath);
d.TraceDetail("%s \n", currpath.c_str() );
//Did we get there??
//Test Mkdir:
d.TraceDetail("Testing Mkdir: \n");
TSTRING makedir(_T("/tmp/tw_mkdir"));
pFSServices->Mkdir(makedir); // throws on error
//Test Rmdir
d.TraceDetail("Testing Rmdir:\n");
TEST( pFSServices->Rmdir(makedir) );
// Test GetMachineName
d.TraceDetail("Testing GetMachineName:\n");
TSTRING uname;
pFSServices->GetMachineName(uname);
d.TraceDetail("GetMachineName returned: %s\n", uname.c_str());
// Test GetHostID
d.TraceDetail("Testing GetHostID:\n");
TSTRING hostid;
pFSServices->GetHostID(hostid);
d.TraceDetail("GetHostID returned: %s\n", hostid.c_str());
// Test GetCurrentUserName
d.TraceDetail("Testing GetCurrentUserName:\n");
TSTRING username;
TEST( pFSServices->GetCurrentUserName(username) );
d.TraceDetail("GetCurrentUserName returned: %s\n", username.c_str());
// Test GetIPAddress
d.TraceDetail("Testing GetIPAddress:\n");
uint32 *ipaddr;
TEST( pFSServices->GetIPAddress( *ipaddr ) );
d.TraceDetail("GetIPAddress returned: %d\n", ipaddr);
// test GetExecutableFilename
d.TraceDetail("Testing GetExecutableFilename: \n");
TSTRING filename = _T("sh");
TSTRING fullpath = _T("/bin/");
TEST(pFSServices->GetExecutableFilename(fullpath, filename));
filename = _T("/bin/sh");
TEST(pFSServices->GetExecutableFilename(fullpath, filename));
// test Rename
d.TraceDetail("Testing Rename:\n");
TSTRING newtestfile = _T("/tmp/new.tmp");
TEST( pFSServices->Rename( testfile, newtestfile ) );
// test GetOwnerForFile
d.TraceDetail("Testing GetOwnerForFile:\n");
TSTRING ownername;
TEST( pFSServices->GetOwnerForFile( newtestfile, ownername ) );
d.TraceDetail("GetOwnerForFile returned owner %s.\n", ownername.c_str());
// test GetGroupForFile
d.TraceDetail("Testing GetGroupForFile:\n");
TSTRING groupname;
TEST( pFSServices->GetGroupForFile( newtestfile, groupname ) );
d.TraceDetail("GetGroupForFile returned group %s.\n", groupname.c_str());
// test FileDelete
d.TraceDetail("Testing FileDelete:\n");
TEST( pFSServices->FileDelete( newtestfile ) );
}//end try block
catch (eError& e)
{
d.TraceError("Exception caught: %s\n", e.GetMsg());
}
}
#endif // IS_UNIX

View File

@ -44,7 +44,7 @@
// parameters of dissimilar types. Therefore, *FwdIter need not be
// the same type as CmpObjT. Uses a binary search algorithm.
//
// Return type : FwdIterT : First element in the sequence [first, last)
// Return type : FwdIterT : First element in the sequence [first, last)
// that is equal to or greater than 'obj' or
// 'last' if there is no such element.
//
@ -60,12 +60,12 @@ template< class FwdIterT, class CmpObjT, class CmpFuncT > FwdIterT UpperBound( F
int nElemsInSet = 0;
FwdIterT iCur = first;
for (; iCur != last; ++iCur )
++nElemsInSet;
++nElemsInSet;
iCur = first;
while( 0 < nElemsInSet )
{
{
// go to halfway point
int iHalfWay = nElemsInSet/2;
FwdIterT iTemp = iCur;
@ -75,15 +75,15 @@ template< class FwdIterT, class CmpObjT, class CmpFuncT > FwdIterT UpperBound( F
if( less( *iTemp, obj ) )
{
// start next search set at next elem with half of the last search set's elements
iCur = ++iTemp;
iCur = ++iTemp;
nElemsInSet -= iHalfWay + 1; // already searched ( iHalfway + 1 ) elems
}
else
else
{
// start next search set beginning with half of the last search set's elements
nElemsInSet = iHalfWay;
nElemsInSet = iHalfWay;
}
}
}
return iCur;
}

View File

@ -49,7 +49,7 @@
iUserNotify* iUserNotify::mpInstance = 0;
iUserNotify::iUserNotify(int verboseLevel) :
mVerboseLevel(verboseLevel)
mVerboseLevel(verboseLevel)
{
}
@ -59,12 +59,12 @@ iUserNotify::~iUserNotify()
void iUserNotify::SetVerboseLevel(int level)
{
mVerboseLevel = level;
mVerboseLevel = level;
}
int iUserNotify::GetVerboseLevel() const
{
return mVerboseLevel;
return mVerboseLevel;
}
///////////////////////////////////////////////////////////////////////////////
@ -74,8 +74,8 @@ void iUserNotify::NotifySilent( const TCHAR* format, ... )
{
va_list args;
va_start(args, format);
HandleNotify( V_SILENT, format, args );
va_end(args);
HandleNotify( V_SILENT, format, args );
va_end(args);
}
///////////////////////////////////////////////////////////////////////////////
@ -85,8 +85,8 @@ void iUserNotify::NotifyNormal( const TCHAR* format, ... )
{
va_list args;
va_start(args, format);
HandleNotify( V_NORMAL, format, args );
va_end(args);
HandleNotify( V_NORMAL, format, args );
va_end(args);
}
///////////////////////////////////////////////////////////////////////////////
@ -96,8 +96,8 @@ void iUserNotify::NotifyVerbose( const TCHAR* format, ... )
{
va_list args;
va_start(args, format);
HandleNotify( V_VERBOSE, format, args );
va_end(args);
HandleNotify( V_VERBOSE, format, args );
va_end(args);
}
///////////////////////////////////////////////////////////////////////////////
@ -107,8 +107,8 @@ void iUserNotify::Notify(int verboseLevel, const TCHAR* format, ...)
{
va_list args;
va_start(args, format);
HandleNotify( verboseLevel, format, args );
va_end(args);
HandleNotify( verboseLevel, format, args );
va_end(args);
}

View File

@ -46,48 +46,48 @@
class iUserNotify
{
public:
// singleton interface; caller is responsible for deleting pointer;
static iUserNotify* GetInstance();
static void SetInstance(iUserNotify* pInst);
virtual void Notify(int verboseLevel, const TCHAR* format, ...) ;
// 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,
// a console application would want an iUserNotify that prints things to stdout)
// If the current verbosity level is less than verboseLevel, nothing will happen.
// singleton interface; caller is responsible for deleting pointer;
static iUserNotify* GetInstance();
static void SetInstance(iUserNotify* pInst);
virtual void Notify(int verboseLevel, const TCHAR* format, ...) ;
// 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,
// a console application would want an iUserNotify that prints things to stdout)
// If the current verbosity level is less than verboseLevel, nothing will happen.
// All output should be sent through the cDisplayEncoder beforehand
// TODO:BAM -- enforce this somehow?
virtual void SetVerboseLevel(int level);
virtual int GetVerboseLevel() const;
// get/set the current verbosity level. Notify()s that occur whose verbosity level
// is greater than the current level will not be processed.
virtual void SetVerboseLevel(int level);
virtual int GetVerboseLevel() const;
// get/set the current verbosity level. Notify()s that occur whose verbosity level
// is greater than the current level will not be processed.
// a convenience enumeration; no one is bound by law to use these
enum VerboseLevel
{
V_SILENT = 0,
V_NORMAL = 1,
V_VERBOSE = 2
};
//
// convenience methods for notifying at these three levels...
//
void NotifySilent ( const TCHAR* format, ... );
void NotifyNormal ( const TCHAR* format, ... );
void NotifyVerbose ( const TCHAR* format, ... );
// a convenience enumeration; no one is bound by law to use these
enum VerboseLevel
{
V_SILENT = 0,
V_NORMAL = 1,
V_VERBOSE = 2
};
//
// convenience methods for notifying at these three levels...
//
void NotifySilent ( const TCHAR* format, ... );
void NotifyNormal ( const TCHAR* format, ... );
void NotifyVerbose ( const TCHAR* format, ... );
iUserNotify(int verboseLevel = 0);
virtual ~iUserNotify();
iUserNotify(int verboseLevel = 0);
virtual ~iUserNotify();
protected:
virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) = 0;
// this is implemented in derived classes to implement the specific type of
// notification desired
int mVerboseLevel;
virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) = 0;
// this is implemented in derived classes to implement the specific type of
// notification desired
int mVerboseLevel;
private:
static iUserNotify* mpInstance;
static iUserNotify* mpInstance;
};
@ -102,29 +102,29 @@ private:
//-----------------------------------------------------------------------------
#define TW_NOTIFY_SILENT\
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_SILENT )\
iUserNotify::GetInstance()->NotifySilent
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_SILENT )\
iUserNotify::GetInstance()->NotifySilent
#define TW_NOTIFY_NORMAL\
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL )\
iUserNotify::GetInstance()->NotifyNormal
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL )\
iUserNotify::GetInstance()->NotifyNormal
#define TW_NOTIFY_VERBOSE\
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_VERBOSE )\
iUserNotify::GetInstance()->NotifyVerbose
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_VERBOSE )\
iUserNotify::GetInstance()->NotifyVerbose
//#############################################################################
// inline implementation
//#############################################################################
inline iUserNotify* iUserNotify::GetInstance()
{
ASSERT(mpInstance != 0);
return mpInstance;
ASSERT(mpInstance != 0);
return mpInstance;
}
inline void iUserNotify::SetInstance(iUserNotify* pInst)
{
mpInstance = pInst;
mpInstance = pInst;
}

View File

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

View File

@ -43,10 +43,10 @@
class cUserNotifyStdout : public iUserNotify
{
public:
virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) ;
// formats the string and sends it to stdout
// 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
virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) ;
// formats the string and sends it to stdout
// 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
};
#endif /* __USERNOTIFYSTDOUT_H */

View File

@ -61,7 +61,7 @@ public:
TCHAR* string;
};
// Select between the different localized string sets
// Select between the different localized string sets
// for this product. Returns false if string not defined.
virtual bool SelectStringSet(int setID) = 0;
@ -83,11 +83,11 @@ public:
// Add a single string. The above rules apply.
virtual void AddString(int setID, int stringID, TCHAR* string) = 0;
// singleton manipulation
static iUserString* GetInstance();
static void SetInstance(iUserString* pInst);
// singleton manipulation
static iUserString* GetInstance();
static void SetInstance(iUserString* pInst);
private:
static iUserString* mpInstance;
static iUserString* mpInstance;
};
///////////////////////////////////////////////////////////////////////////////
@ -116,14 +116,14 @@ Example Use:
///////////////////////////////////////////////////////////////////////////////////////////////////
inline iUserString* iUserString::GetInstance()
{
ASSERT(mpInstance);
ASSERT(mpInstance);
return mpInstance;
return mpInstance;
}
inline void iUserString::SetInstance(iUserString* pInst)
{
mpInstance = pInst;
mpInstance = pInst;
}

View File

@ -73,7 +73,7 @@ const TCHAR* cUserStringMemBased::GetString(int stringID) const
{
// mCurrentStringSet is invallid
ASSERT(false);
return _T("<Bad String Set>");
return _T("<Bad String Set>");
}
StringSet::const_iterator stringItr;
@ -84,7 +84,7 @@ const TCHAR* cUserStringMemBased::GetString(int stringID) const
{
// string not found
ASSERT(false);
return _T("<Missing String>");
return _T("<Missing String>");
}
return stringItr->second;

View File

@ -69,11 +69,11 @@ public:
~cUserStringMemBased();
// the abstract interface
virtual bool SelectStringSet (int setID);
virtual const TCHAR* GetString (int stringID) const;
virtual void ClearStringSet (int id);
virtual void AddStringSet (int setID, const iUserString::tStringPair* pPairArray);
virtual void AddString (int setID, int stringID, TCHAR* string);
virtual bool SelectStringSet (int setID);
virtual const TCHAR* GetString (int stringID) const;
virtual void ClearStringSet (int id);
virtual void AddStringSet (int setID, const iUserString::tStringPair* pPairArray);
virtual void AddString (int setID, int stringID, TCHAR* string);
private:
typedef std::map<int, TCHAR*> StringSet;

View File

@ -97,7 +97,7 @@ wchar_t* cUTF8::allocate( const char* in ) THROW( std::bad_alloc )
//--Convert
out[0] = 0x00; // NOTE: Just in case we fail
out[0] = 0x00; // NOTE: Just in case we fail
#ifdef _DEBUG
//size_t nWritten =
#endif
@ -107,8 +107,8 @@ wchar_t* cUTF8::allocate( const char* in ) THROW( std::bad_alloc )
#ifdef _INTEG2 // Verify Output
if ( nWritten == 0 )
{
cDebug d( "cUTF8::allocate" );
d.TraceError( "MultiByteToWideChar failed with %x\n", ::GetLastError() );
cDebug d( "cUTF8::allocate" );
d.TraceError( "MultiByteToWideChar failed with %x\n", ::GetLastError() );
}
ASSERT( out && TSS_IsValidString( out, nWritten ) );
@ -119,7 +119,7 @@ wchar_t* cUTF8::allocate( const char* in ) THROW( std::bad_alloc )
char* cUTF8::allocate( const wchar_t* in ) THROW( std::bad_alloc )
{
ASSERT( in /*&& TSS_IsValidString( in ) */); // Verify Input
ASSERT( in /*&& TSS_IsValidString( in ) */); // Verify Input
// Allocate required size
size_t N = ::WideCharToMultiByte( CP_UTF8, 0, in, -1,0,0,0,0 );
@ -128,7 +128,7 @@ char* cUTF8::allocate( const wchar_t* in ) THROW( std::bad_alloc )
//--Convert
out[0] = 0x00; // NOTE: Just in case we fail
out[0] = 0x00; // NOTE: Just in case we fail
#ifdef _DEBUG
//size_t nWritten =
#endif
@ -138,8 +138,8 @@ char* cUTF8::allocate( const wchar_t* in ) THROW( std::bad_alloc )
#ifdef _INTEG2 // Verify Output
if ( nWritten == 0 )
{
cDebug d( "cUTF8::allocate" );
d.TraceError( "WideCharToMultiByte failed with %x\n", ::GetLastError() );
cDebug d( "cUTF8::allocate" );
d.TraceError( "WideCharToMultiByte failed with %x\n", ::GetLastError() );
}
ASSERT( out /*&& TSS_IsValidString( out, nWritten ) */);
@ -148,5 +148,5 @@ char* cUTF8::allocate( const wchar_t* in ) THROW( std::bad_alloc )
return out;
}
#endif //_UNICODE
#endif //_UNICODE

View File

@ -61,12 +61,12 @@
// function to safely convert the string to something printable
//-----------------------------------------------------------------------------
#ifdef _UNICODE
# define TSS_UTF8( x ) cUTF8( x ).wstr()
# define TSS_UTF8( x ) cUTF8( x ).wstr()
#else
# define TSS_UTF8( x ) x
# define TSS_UTF8( x ) x
#endif
#ifdef _UNICODE // this class is only needed in unicode builds...
#ifdef _UNICODE // this class is only needed in unicode builds...
//-----------------------------------------------------------------------------
// Entities Declared in this Module

View File

@ -80,7 +80,7 @@ public:
~wc16_string_impl(); // call Release() to delete
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;
@ -119,8 +119,8 @@ void wc16_string::operator = (const wc16_string& rhs)
mpData = rhs.mpData;
if( mpData )
mpData->AddRef();
if( mpData )
mpData->AddRef();
}

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