Common: Code clean up of common

This commit is contained in:
zilmar 2022-10-03 18:34:42 +10:30
parent 82d9027374
commit 92054583d4
31 changed files with 878 additions and 668 deletions

View File

@ -10,8 +10,8 @@ public:
void leave(void);
private:
CriticalSection(const CriticalSection&);
CriticalSection& operator=(const CriticalSection&);
CriticalSection(const CriticalSection &);
CriticalSection & operator=(const CriticalSection &);
void * m_cs;
};
@ -19,7 +19,8 @@ private:
class CGuard
{
public:
CGuard(CriticalSection& sectionName) : m_cs(sectionName)
CGuard(CriticalSection & sectionName) :
m_cs(sectionName)
{
m_cs.enter();
}
@ -27,8 +28,9 @@ public:
{
m_cs.leave();
}
private:
CriticalSection& m_cs;
CGuard(const CGuard& copy);
CGuard &operator=(const CGuard& rhs);
CriticalSection & m_cs;
CGuard(const CGuard & copy);
CGuard & operator=(const CGuard & rhs);
};

View File

@ -6,8 +6,8 @@ class CDateTime
{
public:
CDateTime();
CDateTime & SetToNow (void);
std::string Format (const char * format);
CDateTime & SetToNow(void);
std::string Format(const char * format);
private:
time_t m_time;

View File

@ -2,12 +2,12 @@
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <dlfcn.h>
#include <errno.h>
#include <unistd.h>
#endif
DynLibHandle DynamicLibraryOpen(const char *pccLibraryPath, bool ShowErrors)
DynLibHandle DynamicLibraryOpen(const char * pccLibraryPath, bool ShowErrors)
{
if (pccLibraryPath == nullptr)
{
@ -48,4 +48,3 @@ void * DynamicLibraryGetProc(DynLibHandle Lib, const char * ProcedureName)
return dlsym(Lib, ProcedureName);
#endif
}

View File

@ -95,9 +95,18 @@ bool CFile::Open(const char * lpszFileName, uint32_t nOpenFlags)
ULONG dwShareMode = 0;
dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
if ((nOpenFlags & shareDenyWrite) == shareDenyWrite) { dwShareMode &= ~FILE_SHARE_WRITE; }
if ((nOpenFlags & shareDenyRead) == shareDenyRead) { dwShareMode &= ~FILE_SHARE_READ; }
if ((nOpenFlags & shareExclusive) == shareExclusive) { dwShareMode = 0; }
if ((nOpenFlags & shareDenyWrite) == shareDenyWrite)
{
dwShareMode &= ~FILE_SHARE_WRITE;
}
if ((nOpenFlags & shareDenyRead) == shareDenyRead)
{
dwShareMode &= ~FILE_SHARE_READ;
}
if ((nOpenFlags & shareExclusive) == shareExclusive)
{
dwShareMode = 0;
}
// Map modeNoInherit flag
SECURITY_ATTRIBUTES sa;
@ -138,7 +147,7 @@ bool CFile::Open(const char * lpszFileName, uint32_t nOpenFlags)
CPath file(lpszFileName);
if (!file.Exists())
{
FILE * fp = fopen(lpszFileName,"wb");
FILE * fp = fopen(lpszFileName, "wb");
if (fp)
{
fclose(fp);
@ -231,7 +240,7 @@ bool CFile::Flush()
#endif
}
bool CFile::Write(const void* lpBuf, uint32_t nCount)
bool CFile::Write(const void * lpBuf, uint32_t nCount)
{
if (nCount == 0)
{
@ -259,7 +268,7 @@ bool CFile::Write(const void* lpBuf, uint32_t nCount)
return true;
}
uint32_t CFile::Read(void* lpBuf, uint32_t nCount)
uint32_t CFile::Read(void * lpBuf, uint32_t nCount)
{
if (nCount == 0)
{
@ -345,9 +354,9 @@ bool CFile::SetEndOfFile()
#else
Flush();
#ifdef _WIN32
return _chsize(_fileno((FILE *)m_hFile),GetPosition()) == 0;
return _chsize(_fileno((FILE *)m_hFile), GetPosition()) == 0;
#else
return ftruncate(fileno((FILE *)m_hFile),GetPosition()) == 0;
return ftruncate(fileno((FILE *)m_hFile), GetPosition()) == 0;
#endif
#endif
}

View File

@ -26,15 +26,15 @@ public:
end = 0x2
};
virtual bool Open(const char * lpszFileName, uint32_t nOpenFlags ) = 0;
virtual bool Open(const char * lpszFileName, uint32_t nOpenFlags) = 0;
virtual uint32_t GetPosition() const = 0;
virtual int32_t Seek(int32_t lOff, SeekPosition nFrom) = 0;
virtual bool SetLength(uint32_t dwNewLen) = 0;
virtual uint32_t GetLength() const = 0;
virtual uint32_t Read(void* lpBuf, uint32_t nCount) = 0;
virtual bool Write(const void* lpBuf, uint32_t nCount) = 0;
virtual uint32_t Read(void * lpBuf, uint32_t nCount) = 0;
virtual bool Write(const void * lpBuf, uint32_t nCount) = 0;
virtual bool Flush() = 0;
virtual bool Close() = 0;
@ -51,18 +51,18 @@ public:
virtual ~CFile();
virtual bool Open(const char * lpszFileName, uint32_t nOpenFlags );
virtual bool Open(const char * lpszFileName, uint32_t nOpenFlags);
uint32_t SeekToEnd ( void );
void SeekToBegin ( void );
uint32_t SeekToEnd(void);
void SeekToBegin(void);
virtual uint32_t GetPosition() const;
virtual int32_t Seek(int32_t lOff, SeekPosition nFrom);
virtual bool SetLength(uint32_t dwNewLen);
virtual uint32_t GetLength() const;
virtual uint32_t Read(void* lpBuf, uint32_t nCount);
virtual bool Write(const void* lpBuf, uint32_t nCount);
virtual uint32_t Read(void * lpBuf, uint32_t nCount);
virtual bool Write(const void * lpBuf, uint32_t nCount);
virtual bool Flush();
virtual bool Close();
@ -70,8 +70,8 @@ public:
virtual bool SetEndOfFile();
private:
CFile(const CFile&);
CFile& operator=(const CFile&);
CFile(const CFile &);
CFile & operator=(const CFile &);
void * m_hFile;
bool m_bCloseOnDelete;

View File

@ -1,7 +1,7 @@
#include "HighResTimeStamp.h"
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#else
@ -10,7 +10,7 @@
#ifdef _WIN32
bool HighResTimeStamp::m_GotFreq = false;
uint64_t HighResTimeStamp::m_Freq = { 0 };
uint64_t HighResTimeStamp::m_Freq = {0};
#endif
HighResTimeStamp::HighResTimeStamp()

View File

@ -5,7 +5,7 @@ class HighResTimeStamp
{
public:
HighResTimeStamp();
HighResTimeStamp & SetToNow (void);
HighResTimeStamp & SetToNow(void);
uint64_t GetMicroSeconds(void);
void SetMicroSeconds(uint64_t MicroSeconds);

View File

@ -1,7 +1,7 @@
#include "IniFile.h"
#include "StdString.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdlib.h>
CIniFileBase::CIniFileBase(CFileBase & FileObject, const char * FileName) :
m_lastSectionSearch(0),
@ -23,7 +23,10 @@ CIniFileBase::~CIniFileBase(void)
void CIniFileBase::fInsertSpaces(int Pos, int NoOfSpaces)
{
enum { fIS_MvSize = 0x2000 };
enum
{
fIS_MvSize = 0x2000
};
unsigned char Data[fIS_MvSize + 1];
int SizeToRead, result;
@ -39,7 +42,10 @@ void CIniFileBase::fInsertSpaces(int Pos, int NoOfSpaces)
do
{
SizeToRead = end - Pos;
if (SizeToRead > fIS_MvSize) { SizeToRead = fIS_MvSize; }
if (SizeToRead > fIS_MvSize)
{
SizeToRead = fIS_MvSize;
}
if (SizeToRead > 0)
{
m_File.Seek(SizeToRead * -1, CFileBase::current);
@ -63,7 +69,10 @@ void CIniFileBase::fInsertSpaces(int Pos, int NoOfSpaces)
do
{
SizeToRead = end - ReadPos;
if (SizeToRead > fIS_MvSize) { SizeToRead = fIS_MvSize; }
if (SizeToRead > fIS_MvSize)
{
SizeToRead = fIS_MvSize;
}
m_File.Seek(ReadPos, CFileBase::begin);
m_File.Read(Data, SizeToRead);
m_File.Seek(WritePos, CFileBase::begin);
@ -82,9 +91,12 @@ void CIniFileBase::fInsertSpaces(int Pos, int NoOfSpaces)
}
}
int CIniFileBase::GetStringFromFile(char * & String, std::unique_ptr<char> &Data, int & MaxDataSize, int & DataSize, int & ReadPos)
int CIniFileBase::GetStringFromFile(char *& String, std::unique_ptr<char> & Data, int & MaxDataSize, int & DataSize, int & ReadPos)
{
enum { BufferIncrease = 0x2000 };
enum
{
BufferIncrease = 0x2000
};
if (MaxDataSize == 0)
{
ReadPos = 0;
@ -209,7 +221,7 @@ void CIniFileBase::SaveCurrentSection(void)
int MaxDataSize = 0, DataSize = 0, ReadPos = 0, result;
std::unique_ptr<char> Data;
char *Input = nullptr;
char * Input = nullptr;
// Skip first line as it is the section name
int StartPos = m_CurrentSectionFilePos;
@ -217,7 +229,10 @@ void CIniFileBase::SaveCurrentSection(void)
do
{
result = GetStringFromFile(Input, Data, MaxDataSize, DataSize, ReadPos);
if (result <= 1) { continue; }
if (result <= 1)
{
continue;
}
if (strlen(CleanLine(Input)) <= 1 || Input[0] != '[')
{
EndPos = (long)((m_File.GetPosition() - DataSize) + ReadPos);
@ -298,7 +313,7 @@ bool CIniFileBase::MoveToSectionNameData(const char * lpSectionName, bool Change
}
std::unique_ptr<char> Data;
char *Input = nullptr;
char * Input = nullptr;
int MaxDataSize = 0, DataSize = 0, ReadPos = 0, result;
FILELOC_ITR iter = m_SectionsPos.find(std::string(lpSectionName));
@ -326,8 +341,14 @@ bool CIniFileBase::MoveToSectionNameData(const char * lpSectionName, bool Change
do
{
result = GetStringFromFile(Input, Data, MaxDataSize, DataSize, ReadPos);
if (result <= 1) { continue; }
if (strlen(CleanLine(Input)) <= 1) { continue; }
if (result <= 1)
{
continue;
}
if (strlen(CleanLine(Input)) <= 1)
{
continue;
}
// We only care about sections
char * CurrentSection = Input;
@ -337,9 +358,15 @@ bool CIniFileBase::MoveToSectionNameData(const char * lpSectionName, bool Change
CurrentSection += 3;
}
if (CurrentSection[0] != '[') { continue; }
if (CurrentSection[0] != '[')
{
continue;
}
int lineEndPos = (int)strlen(CurrentSection) - 1;
if (CurrentSection[lineEndPos] != ']') { continue; }
if (CurrentSection[lineEndPos] != ']')
{
continue;
}
// Take off the ']' from the end of the string
CurrentSection[lineEndPos] = 0;
CurrentSection += 1;
@ -383,11 +410,23 @@ bool CIniFileBase::MoveToSectionNameData(const char * lpSectionName, bool Change
do
{
result = GetStringFromFile(Input, Data, MaxDataSize, DataSize, ReadPos);
if (result <= 1) { continue; }
if (strlen(CleanLine(Input)) <= 1) { continue; }
if (Input[0] == '[') { break; }
if (result <= 1)
{
continue;
}
if (strlen(CleanLine(Input)) <= 1)
{
continue;
}
if (Input[0] == '[')
{
break;
}
char * Pos = strchr(Input, '=');
if (Pos == nullptr) { continue; }
if (Pos == nullptr)
{
continue;
}
char * Value = &Pos[1];
char * Pos1 = Pos - 1;
@ -442,7 +481,10 @@ const char * CIniFileBase::CleanLine(char * Line)
// Strip any spaces or line feeds from the end of the line
for (int count = (int)strlen(&Line[0]) - 1; count >= 0; count--)
{
if (Line[count] != ' ' && Line[count] != '\r') { break; }
if (Line[count] != ' ' && Line[count] != '\r')
{
break;
}
Line[count] = 0;
}
return Line;
@ -502,7 +544,10 @@ bool CIniFileBase::DeleteSection(const char * lpSectionName)
{
CGuard Guard(m_CS);
if (!m_File.IsOpen()) { return false; }
if (!m_File.IsOpen())
{
return false;
}
SaveCurrentSection();
if (!MoveToSectionNameData(lpSectionName, true))
@ -515,13 +560,19 @@ bool CIniFileBase::DeleteSection(const char * lpSectionName)
{
int MaxDataSize = 0, DataSize = 0, ReadPos = 0, NextLine = 0, result;
std::unique_ptr <char> Data;
char *Input = nullptr;
std::unique_ptr<char> Data;
char * Input = nullptr;
do
{
result = GetStringFromFile(Input, Data, MaxDataSize, DataSize, ReadPos);
if (result <= 1) { continue; }
if (strlen(CleanLine(Input)) <= 1) { continue; }
if (result <= 1)
{
continue;
}
if (strlen(CleanLine(Input)) <= 1)
{
continue;
}
if (Input[0] != '[')
{
@ -540,13 +591,19 @@ bool CIniFileBase::DeleteSection(const char * lpSectionName)
long ReadPos = NextSectionStart;
long WritePos = DeleteSectionStart;
enum { fIS_MvSize = 0x2000 };
enum
{
fIS_MvSize = 0x2000
};
unsigned char Data[fIS_MvSize + 1];
int SizeToRead;
do
{
SizeToRead = end - ReadPos;
if (SizeToRead > fIS_MvSize) { SizeToRead = fIS_MvSize; }
if (SizeToRead > fIS_MvSize)
{
SizeToRead = fIS_MvSize;
}
m_File.Seek(ReadPos, CFileBase::begin);
m_File.Read(Data, SizeToRead);
m_File.Seek(WritePos, CFileBase::begin);
@ -774,7 +831,7 @@ void CIniFileBase::SetAutoFlush(bool AutoFlush)
}
}
void CIniFileBase::GetKeyList(const char * lpSectionName, strlist &List)
void CIniFileBase::GetKeyList(const char * lpSectionName, strlist & List)
{
List.clear();
@ -817,19 +874,34 @@ void CIniFileBase::GetKeyValueData(const char * lpSectionName, KeyValueData & Li
strSection = lpSectionName;
}
if (!MoveToSectionNameData(strSection.c_str(), false)) { return; }
if (!MoveToSectionNameData(strSection.c_str(), false))
{
return;
}
int MaxDataSize = 0, DataSize = 0, ReadPos = 0, result;
std::unique_ptr<char> Data;
char *Input = nullptr;
char * Input = nullptr;
do
{
result = GetStringFromFile(Input, Data, MaxDataSize, DataSize, ReadPos);
if (result <= 1) { continue; }
if (strlen(CleanLine(Input)) <= 1) { continue; }
if (Input[0] == '[') { break; }
if (result <= 1)
{
continue;
}
if (strlen(CleanLine(Input)) <= 1)
{
continue;
}
if (Input[0] == '[')
{
break;
}
char * Pos = strchr(Input, '=');
if (Pos == nullptr) { continue; }
if (Pos == nullptr)
{
continue;
}
Pos[0] = 0;
List.insert(KeyValueData::value_type(stdstr(Input).Trim(), &Pos[1]));

View File

@ -4,15 +4,15 @@
#include <strings.h>
#endif
#include "Platform.h"
#include "File.h"
#include "CriticalSection.h"
#include <string>
#include <map>
#include <vector>
#include "File.h"
#include "Platform.h"
#include <list>
#include <set>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
class CIniFileBase
{
@ -22,7 +22,7 @@ public:
typedef std::list<std::string> strlist;
typedef std::pair<const std::string *, const std::string *> KeyValueItem;
typedef std::vector<KeyValueItem> KeyValueVector;
typedef void(*SortData)(KeyValueVector &);
typedef void (*SortData)(KeyValueVector &);
CIniFileBase(CFileBase & FileObject, const char * FileName);
virtual ~CIniFileBase(void);
@ -42,12 +42,15 @@ public:
void SetAutoFlush(bool AutoFlush);
void FlushChanges(void);
bool EntryExists(const char * lpSectionName, const char * lpKeyName);
void GetKeyList(const char * lpSectionName, strlist &List);
void GetKeyList(const char * lpSectionName, strlist & List);
void GetKeyValueData(const char * lpSectionName, KeyValueData & List);
void SetCustomSort(SortData SortFunction);
void GetVectorOfSections(SectionList & sections);
const std::string &GetFileName() { return m_FileName; }
const std::string & GetFileName()
{
return m_FileName;
}
protected:
void OpenIniFileReadOnly();
@ -62,7 +65,7 @@ protected:
private:
struct insensitive_compare
{
bool operator() (const std::string & a, const std::string & b) const
bool operator()(const std::string & a, const std::string & b) const
{
return _stricmp(a.c_str(), b.c_str()) < 0;
}
@ -88,7 +91,7 @@ private:
SortData m_SortFunction;
void fInsertSpaces(int Pos, int NoOfSpaces);
int GetStringFromFile(char * & String, std::unique_ptr<char> &Data, int & MaxDataSize, int & DataSize, int & ReadPos);
int GetStringFromFile(char *& String, std::unique_ptr<char> & Data, int & MaxDataSize, int & DataSize, int & ReadPos);
bool MoveToSectionNameData(const char * lpSectionName, bool ChangeCurrentSection);
const char * CleanLine(char * Line);
void ClearSectionPosList(long FilePos);

View File

@ -1,10 +1,10 @@
#include "Log.h"
#include "path.h"
#include "Platform.h"
#include <stdio.h>
#include "path.h"
#include <stdarg.h>
#include <stdio.h>
CLog::CLog (void ) :
CLog::CLog(void) :
m_FlushOnWrite(false),
m_TruncateFileLog(true),
m_MaxFileSize(MAX_FILE_SIZE),
@ -13,11 +13,11 @@ CLog::CLog (void ) :
{
}
CLog::~CLog (void)
CLog::~CLog(void)
{
}
bool CLog::Open( const char * FileName, LOG_OPEN_MODE mode /* = Log_New */)
bool CLog::Open(const char * FileName, LOG_OPEN_MODE mode /* = Log_New */)
{
if (FileName == nullptr)
{
@ -31,19 +31,22 @@ bool CLog::Open( const char * FileName, LOG_OPEN_MODE mode /* = Log_New */)
}
uint32_t nOpenFlags = CFile::modeReadWrite | CFile::modeCreate;
if (mode == Log_Append) { nOpenFlags |= CFile::modeNoTruncate; }
if (mode == Log_Append)
{
nOpenFlags |= CFile::modeNoTruncate;
}
if (!m_hLogFile.Open(File, nOpenFlags))
{
return false;
}
m_FileName = (const char *)File;
m_hLogFile.Seek(0,mode == Log_Append ? CFile::end : CFile::begin);
m_hLogFile.Seek(0, mode == Log_Append ? CFile::end : CFile::begin);
m_FileSize = mode == Log_Append ? (uint32_t)m_hLogFile.GetLength() : 0;
return true;
}
void CLog::Close ( void )
void CLog::Close(void)
{
if (m_hLogFile.IsOpen())
{
@ -54,14 +57,17 @@ void CLog::Close ( void )
void CLog::LogF(const char * Message, ...)
{
va_list ap;
va_start( ap, Message );
LogArgs(Message,ap);
va_end( ap );
va_start(ap, Message);
LogArgs(Message, ap);
va_end(ap);
}
void CLog::LogArgs(const char * Message, va_list & args )
void CLog::LogArgs(const char * Message, va_list & args)
{
if (!m_hLogFile.IsOpen()) { return; }
if (!m_hLogFile.IsOpen())
{
return;
}
try
{
@ -74,15 +80,18 @@ void CLog::LogArgs(const char * Message, va_list & args )
Log(Msg);
}
}
catch(...)
catch (...)
{
Log("Invalid message format");
}
}
void CLog::Log( const char * Message )
void CLog::Log(const char * Message)
{
if (!m_hLogFile.IsOpen()) { return; }
if (!m_hLogFile.IsOpen())
{
return;
}
uint32_t message_len = (uint32_t)strlen(Message);
m_hLogFile.Write(Message, message_len);
if (m_FlushOnWrite)
@ -107,14 +116,14 @@ void CLog::Log( const char * Message )
uint32_t end = (uint32_t)m_hLogFile.SeekToEnd();
// Move to reduce size
m_hLogFile.Seek((end - m_MaxFileSize) + m_FileChangeSize,CFile::begin);
m_hLogFile.Seek((end - m_MaxFileSize) + m_FileChangeSize, CFile::begin);
// Find next end of line
uint32_t NextEnter = 0, dwRead = 0;
do
{
uint8_t Data[300];
dwRead = m_hLogFile.Read(Data,sizeof(Data));
dwRead = m_hLogFile.Read(Data, sizeof(Data));
if (dwRead == 0)
{
break;
@ -130,26 +139,32 @@ void CLog::Log( const char * Message )
}
}
NextEnter += dwRead;
} while(dwRead != 0);
} while (dwRead != 0);
// Copy content of log to the new file
uint32_t ReadPos = (end - m_MaxFileSize) + m_FileChangeSize + NextEnter;
uint32_t SizeToRead, WritePos = 0;
do
{
enum { fIS_MvSize = 0x5000 };
enum
{
fIS_MvSize = 0x5000
};
unsigned char Data[fIS_MvSize + 1];
SizeToRead = end - ReadPos;
if (SizeToRead > fIS_MvSize) { SizeToRead = fIS_MvSize; }
if (SizeToRead > fIS_MvSize)
{
SizeToRead = fIS_MvSize;
}
m_hLogFile.Seek(ReadPos,CFile::begin);
m_hLogFile.Seek(ReadPos, CFile::begin);
dwRead = m_hLogFile.Read(Data,SizeToRead);
dwRead = m_hLogFile.Read(Data, SizeToRead);
m_hLogFile.Seek(WritePos,CFile::begin);
m_hLogFile.Seek(WritePos, CFile::begin);
if (!m_hLogFile.Write(Data,dwRead))
if (!m_hLogFile.Write(Data, dwRead))
{
//BreakPoint(__FILE__,__LINE__);
break;
@ -169,7 +184,10 @@ void CLog::Log( const char * Message )
bool CLog::Empty(void)
{
if (!m_hLogFile.IsOpen()) { return true; }
if (!m_hLogFile.IsOpen())
{
return true;
}
if (m_hLogFile.GetLength() == 0)
{
return true;

View File

@ -1,18 +1,25 @@
#pragma once
#include "File.h"
#include <stdarg.h>
#include <string>
#include "File.h"
class CLog
{
public:
enum LOG_OPEN_MODE
{
Log_New, Log_Append
Log_New,
Log_Append
};
enum { MB = 1024 * 1024 };
enum { MAX_FILE_SIZE = 10 * MB };
enum
{
MB = 1024 * 1024
};
enum
{
MAX_FILE_SIZE = 10 * MB
};
CLog(void);
~CLog(void);
@ -29,15 +36,30 @@ public:
m_MaxFileSize = Size;
m_FileChangeSize = (uint32_t)(Size * 0.1);
}
inline void SetTruncateFile(bool Truncate) { m_TruncateFileLog = Truncate; }
inline void SetFlush(bool Always) { m_FlushOnWrite = Always; }
inline bool IsOpen(void) const { return m_hLogFile.IsOpen(); }
inline bool Flush(void) { return m_hLogFile.Flush(); }
inline const std::string & FileName(void) const { return m_FileName; }
inline void SetTruncateFile(bool Truncate)
{
m_TruncateFileLog = Truncate;
}
inline void SetFlush(bool Always)
{
m_FlushOnWrite = Always;
}
inline bool IsOpen(void) const
{
return m_hLogFile.IsOpen();
}
inline bool Flush(void)
{
return m_hLogFile.Flush();
}
inline const std::string & FileName(void) const
{
return m_FileName;
}
private:
CLog(const CLog&);
CLog& operator=(const CLog&);
CLog(const CLog &);
CLog & operator=(const CLog &);
CFile m_hLogFile;
bool m_FlushOnWrite;

View File

@ -38,7 +38,7 @@ private:
uint32_t m_NextOrder;
};
CMemList *MemList(void)
CMemList * MemList(void)
{
static CMemList m_MemList;
@ -118,8 +118,8 @@ void CMemList::removeItem(void * ptr)
void CMemList::DumpItems(void)
{
char path_buffer[_MAX_PATH] = { 0 }, drive[_MAX_DRIVE] = { 0 }, dir[_MAX_DIR] = { 0 };
char fname[_MAX_FNAME] = { 0 }, ext[_MAX_EXT] = { 0 }, LogFileName[_MAX_PATH] = { 0 };
char path_buffer[_MAX_PATH] = {0}, drive[_MAX_DRIVE] = {0}, dir[_MAX_DIR] = {0};
char fname[_MAX_FNAME] = {0}, ext[_MAX_EXT] = {0}, LogFileName[_MAX_PATH] = {0};
GetModuleFileNameA(m_hModule, path_buffer, sizeof(path_buffer));
_splitpath(path_buffer, drive, dir, fname, ext);
@ -128,7 +128,7 @@ void CMemList::DumpItems(void)
HANDLE hLogFile = INVALID_HANDLE_VALUE;
do
{
hLogFile = CreateFileA( LogFileName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr );
hLogFile = CreateFileA(LogFileName, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
if (hLogFile == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_SHARING_VIOLATION)
@ -169,7 +169,7 @@ void CMemList::DumpItems(void)
}
}
void* AllocateMemory(size_t size, const char* filename, unsigned int line)
void * AllocateMemory(size_t size, const char * filename, unsigned int line)
{
void * res = malloc(size);
if (res == nullptr)
@ -183,22 +183,22 @@ void* AllocateMemory(size_t size, const char* filename, unsigned int line)
return res;
}
void* operator new (size_t size, const char* filename, unsigned int line)
void * operator new(size_t size, const char * filename, unsigned int line)
{
return AllocateMemory(size, filename, line);
}
void* operator new[] (size_t size, const char* filename, unsigned int line)
void * operator new[](size_t size, const char * filename, unsigned int line)
{
return AllocateMemory(size, filename, line);
}
void* operator new (size_t size)
void * operator new(size_t size)
{
return AllocateMemory(size, "Unknown", 0);
}
void operator delete (void* ptr)
void operator delete(void * ptr)
{
free(ptr);
if (!InInit)
@ -207,17 +207,17 @@ void operator delete (void* ptr)
}
}
void operator delete[](void* ptr)
void operator delete[](void * ptr)
{
delete ptr;
}
void operator delete (void* ptr, const char* /*filename*/, unsigned int /*line*/)
void operator delete(void * ptr, const char * /*filename*/, unsigned int /*line*/)
{
delete ptr;
}
void operator delete[](void* ptr, const char* /*filename*/, unsigned int /*line*/)
void operator delete[](void * ptr, const char * /*filename*/, unsigned int /*line*/)
{
delete ptr;
}

View File

@ -6,11 +6,11 @@
#ifdef MEM_LEAK_TEST
void* operator new (size_t size, const char* filename, unsigned int line);
void* operator new[](size_t size, const char* filename, unsigned int line);
void operator delete (void* ptr, const char* filename, unsigned int line);
void operator delete[](void* ptr, const char* filename, unsigned int line);
void * operator new(size_t size, const char * filename, unsigned int line);
void * operator new[](size_t size, const char * filename, unsigned int line);
void operator delete(void * ptr, const char * filename, unsigned int line);
void operator delete[](void * ptr, const char * filename, unsigned int line);
#define new new(__FILE__, __LINE__)
#define new new (__FILE__, __LINE__)
#endif

View File

@ -48,12 +48,12 @@ static bool TranslateToMemProtect(int OsMemProtection, MEM_PROTECTION & memProte
}
#endif
void* AllocateAddressSpace(size_t size, void * base_address)
void * AllocateAddressSpace(size_t size, void * base_address)
{
#ifdef _WIN32
return VirtualAlloc(base_address, size, MEM_RESERVE | MEM_TOP_DOWN, PAGE_NOACCESS);
#else
void * ptr = mmap((void*)0, size, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
void * ptr = mmap((void *)0, size, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
if (ptr == MAP_FAILED)
{
return nullptr;
@ -63,7 +63,7 @@ void* AllocateAddressSpace(size_t size, void * base_address)
#endif
}
bool FreeAddressSpace(void* addr, size_t size)
bool FreeAddressSpace(void * addr, size_t size)
{
#ifdef _WIN32
size = 0; // Unused
@ -75,7 +75,7 @@ bool FreeAddressSpace(void* addr, size_t size)
#endif
}
void* CommitMemory(void* addr, size_t size, MEM_PROTECTION memProtection)
void * CommitMemory(void * addr, size_t size, MEM_PROTECTION memProtection)
{
int OsMemProtection;
if (!TranslateFromMemProtect(memProtection, OsMemProtection))
@ -91,10 +91,10 @@ void* CommitMemory(void* addr, size_t size, MEM_PROTECTION memProtection)
#endif
}
bool DecommitMemory(void* addr, size_t size)
bool DecommitMemory(void * addr, size_t size)
{
#ifdef _WIN32
return VirtualFree((void*)addr, size, MEM_DECOMMIT) != 0;
return VirtualFree((void *)addr, size, MEM_DECOMMIT) != 0;
#else
// Instead of unmapping the address, we're just gonna trick
// the TLB to mark this as a new mapped area which, due to
@ -107,7 +107,7 @@ bool DecommitMemory(void* addr, size_t size)
#endif
}
bool ProtectMemory(void* addr, size_t size, MEM_PROTECTION memProtection, MEM_PROTECTION * OldProtect)
bool ProtectMemory(void * addr, size_t size, MEM_PROTECTION memProtection, MEM_PROTECTION * OldProtect)
{
int OsMemProtection;
if (!TranslateFromMemProtect(memProtection, OsMemProtection))

View File

@ -9,8 +9,8 @@ enum MEM_PROTECTION
MEM_EXECUTE_READWRITE,
};
void* AllocateAddressSpace(size_t size, void * base_address = 0);
bool FreeAddressSpace(void* addr, size_t size);
void* CommitMemory(void* addr, size_t size, MEM_PROTECTION memProtection);
bool DecommitMemory(void* addr, size_t size);
bool ProtectMemory(void* addr, size_t size, MEM_PROTECTION memProtection, MEM_PROTECTION * OldProtect = nullptr);
void * AllocateAddressSpace(size_t size, void * base_address = 0);
bool FreeAddressSpace(void * addr, size_t size);
void * CommitMemory(void * addr, size_t size, MEM_PROTECTION memProtection);
bool DecommitMemory(void * addr, size_t size);
bool ProtectMemory(void * addr, size_t size, MEM_PROTECTION memProtection, MEM_PROTECTION * OldProtect = nullptr);

View File

@ -1,7 +1,7 @@
#include "Platform.h"
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#ifndef _WIN32
int _vscprintf(const char * format, va_list pargs)
@ -20,12 +20,24 @@ int _vscprintf(const char * format, va_list pargs)
int fesetround(int RoundType)
{
static const unsigned int msRound[4] = { _RC_NEAR, _RC_CHOP, _RC_UP, _RC_DOWN };
static const unsigned int msRound[4] = {_RC_NEAR, _RC_CHOP, _RC_UP, _RC_DOWN};
int32_t res = _controlfp(msRound[RoundType], _MCW_RC);
if (res == _RC_NEAR) { return FE_TONEAREST; }
if (res == _RC_CHOP) { return FE_TOWARDZERO; }
if (res == _RC_UP) { return FE_UPWARD; }
if (res == _RC_DOWN) { return FE_DOWNWARD; }
if (res == _RC_NEAR)
{
return FE_TONEAREST;
}
if (res == _RC_CHOP)
{
return FE_TOWARDZERO;
}
if (res == _RC_UP)
{
return FE_UPWARD;
}
if (res == _RC_DOWN)
{
return FE_DOWNWARD;
}
return FE_TONEAREST;
}
#endif

View File

@ -10,13 +10,19 @@
#define _snprintf snprintf
#define _isnan isnan
int _vscprintf (const char * format, va_list pargs);
int _vscprintf(const char * format, va_list pargs);
#endif
// FPU rounding code
#ifdef _WIN32
typedef enum { FE_TONEAREST = 0, FE_TOWARDZERO, FE_UPWARD, FE_DOWNWARD } eRoundType;
typedef enum
{
FE_TONEAREST = 0,
FE_TOWARDZERO,
FE_UPWARD,
FE_DOWNWARD,
} eRoundType;
int fesetround(int RoundType);
#else
#include <fenv.h>

View File

@ -1,7 +1,7 @@
#include "StdString.h"
#include "Platform.h"
#include <malloc.h>
#include <algorithm>
#include <malloc.h>
#ifdef _WIN32
#include <Windows.h>
#endif
@ -67,7 +67,7 @@ strvector stdstr::Tokenize(char delimiter) const
void stdstr::ArgFormat(const char * strFormat, va_list & args)
{
#pragma warning(push)
#pragma warning(disable:4996)
#pragma warning(disable : 4996)
size_t nlen = _vscprintf(strFormat, args) + 1;
char * buffer = (char *)alloca(nlen * sizeof(char));
@ -88,21 +88,21 @@ void stdstr::Format(const char * strFormat, ...)
va_end(args);
}
stdstr& stdstr::ToLower(void)
stdstr & stdstr::ToLower(void)
{
std::transform(begin(), end(), begin(), (char(*)(int)) tolower);
std::transform(begin(), end(), begin(), (char (*)(int))tolower);
return *this;
}
stdstr& stdstr::ToUpper(void)
stdstr & stdstr::ToUpper(void)
{
std::transform(begin(), end(), begin(), (char(*)(int)) toupper);
std::transform(begin(), end(), begin(), (char (*)(int))toupper);
return *this;
}
void stdstr::Replace(const char search, const char replace)
{
std::string& str = *this;
std::string & str = *this;
std::string::size_type pos = str.find(search);
while (pos != std::string::npos)
{
@ -113,7 +113,7 @@ void stdstr::Replace(const char search, const char replace)
void stdstr::Replace(const char * search, const char replace)
{
std::string& str = *this;
std::string & str = *this;
std::string::size_type pos = str.find(search);
size_t SearchSize = strlen(search);
while (pos != std::string::npos)
@ -123,9 +123,9 @@ void stdstr::Replace(const char * search, const char replace)
}
}
void stdstr::Replace(const std::string& search, const std::string& replace)
void stdstr::Replace(const std::string & search, const std::string & replace)
{
std::string& str = *this;
std::string & str = *this;
std::string::size_type pos = str.find(search);
size_t SearchSize = search.size();
while (pos != std::string::npos)

View File

@ -2,10 +2,10 @@
class stdstr;
#include <stdarg.h>
#include <vector>
#include <string>
#include <list>
#include <stdarg.h>
#include <string>
#include <vector>
typedef std::vector<stdstr> strvector;
@ -27,8 +27,8 @@ public:
strvector Tokenize(char delimiter) const;
strvector Tokenize(const char * delimiter) const;
void Format(const char * strFormat, ...);
stdstr& ToLower(void);
stdstr& ToUpper(void);
stdstr & ToLower(void);
stdstr & ToUpper(void);
void Replace(const char search, const char replace);
void Replace(const char * search, const char replace);
@ -56,7 +56,7 @@ public:
class stdwstr_f : public std::wstring
{
public:
stdwstr_f(const wchar_t * strFormat, ... );
stdwstr_f(const wchar_t * strFormat, ...);
};
#endif

View File

@ -13,8 +13,8 @@ SyncEvent::SyncEvent(bool bManualReset)
m_signalled = false;
m_Event = new pthread_mutex_t;
m_cond = new pthread_cond_t;
pthread_mutex_init((pthread_mutex_t*)m_Event, nullptr);
pthread_cond_init((pthread_cond_t*)m_cond, nullptr);
pthread_mutex_init((pthread_mutex_t *)m_Event, nullptr);
pthread_cond_init((pthread_cond_t *)m_cond, nullptr);
#endif
}
@ -23,10 +23,10 @@ SyncEvent::~SyncEvent()
#ifdef _WIN32
CloseHandle(m_Event);
#else
pthread_mutex_destroy((pthread_mutex_t*)m_Event);
pthread_cond_destroy((pthread_cond_t*)m_cond);
delete (pthread_mutex_t*)m_Event;
delete (pthread_cond_t*)m_cond;
pthread_mutex_destroy((pthread_mutex_t *)m_Event);
pthread_cond_destroy((pthread_cond_t *)m_cond);
delete (pthread_mutex_t *)m_Event;
delete (pthread_cond_t *)m_cond;
#endif
}
@ -35,10 +35,10 @@ void SyncEvent::Trigger()
#ifdef _WIN32
SetEvent(m_Event);
#else
pthread_mutex_lock((pthread_mutex_t*)m_Event);
pthread_mutex_lock((pthread_mutex_t *)m_Event);
m_signalled = true;
pthread_mutex_unlock((pthread_mutex_t*)m_Event);
pthread_cond_signal((pthread_cond_t*)m_cond);
pthread_mutex_unlock((pthread_mutex_t *)m_Event);
pthread_cond_signal((pthread_cond_t *)m_cond);
#endif
}
@ -47,12 +47,12 @@ bool SyncEvent::IsTriggered(int32_t iWaitTime) const
#ifdef _WIN32
return (WAIT_OBJECT_0 == WaitForSingleObject(m_Event, iWaitTime));
#else
pthread_mutex_lock((pthread_mutex_t*)m_Event);
pthread_mutex_lock((pthread_mutex_t *)m_Event);
while (!m_signalled)
{
pthread_cond_wait((pthread_cond_t*)m_cond, (pthread_mutex_t*)m_Event);
pthread_cond_wait((pthread_cond_t *)m_cond, (pthread_mutex_t *)m_Event);
}
pthread_mutex_unlock((pthread_mutex_t*)m_Event);
pthread_mutex_unlock((pthread_mutex_t *)m_Event);
return true;
#endif
}
@ -62,9 +62,9 @@ void SyncEvent::Reset()
#ifdef _WIN32
ResetEvent(m_Event);
#else
pthread_mutex_lock((pthread_mutex_t*)m_Event);
pthread_mutex_lock((pthread_mutex_t *)m_Event);
m_signalled = false;
pthread_mutex_unlock((pthread_mutex_t*)m_Event);
pthread_mutex_unlock((pthread_mutex_t *)m_Event);
#endif
}

View File

@ -4,19 +4,22 @@
class SyncEvent
{
public:
enum { INFINITE_TIMEOUT = 0xFFFFFFFF };
enum
{
INFINITE_TIMEOUT = 0xFFFFFFFF
};
SyncEvent(bool bManualReset = true);
~SyncEvent(void);
void Trigger (void);
bool IsTriggered (int32_t iWaitTime = 0) const;
void Trigger(void);
bool IsTriggered(int32_t iWaitTime = 0) const;
void Reset();
void * GetHandle();
protected:
SyncEvent(const SyncEvent&);
SyncEvent& operator=(const SyncEvent&);
SyncEvent(const SyncEvent &);
SyncEvent & operator=(const SyncEvent &);
void * m_Event;
#ifndef _WIN32

View File

@ -4,9 +4,9 @@
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
CThread::CThread(CTHREAD_START_ROUTINE lpStartAddress) :
@ -48,15 +48,15 @@ bool CThread::Start(void * lpThreadParameter)
#else
pthread_t * thread_id = new pthread_t;
m_thread = (void*)thread_id;
m_thread = (void *)thread_id;
int res = pthread_create(thread_id, nullptr, (void *(*)(void *))ThreadWrapper, this);
int res = pthread_create(thread_id, nullptr, (void * (*)(void *))ThreadWrapper, this);
#endif
WriteTrace(TraceThread, TraceDebug, "Done");
return true;
}
void * CThread::ThreadWrapper (CThread * _this)
void * CThread::ThreadWrapper(CThread * _this)
{
WriteTrace(TraceThread, TraceDebug, "Start");
_this->m_threadID = CThread::GetCurrentThreadId();

View File

@ -5,16 +5,19 @@ class CThread
{
public:
#ifdef _WIN32
typedef uint32_t(*CTHREAD_START_ROUTINE)(void * lpThreadParameter);
typedef uint32_t (*CTHREAD_START_ROUTINE)(void * lpThreadParameter);
#else
typedef void *(*CTHREAD_START_ROUTINE)(void *);
typedef void * (*CTHREAD_START_ROUTINE)(void *);
#endif
CThread(CTHREAD_START_ROUTINE lpStartAddress);
~CThread();
bool Start(void * lpThreadParameter);
inline uint32_t ThreadID(void) const { return m_threadID; }
inline uint32_t ThreadID(void) const
{
return m_threadID;
}
bool isRunning(void) const;
void Terminate(void);
@ -22,10 +25,10 @@ public:
private:
CThread(void);
CThread(const CThread&);
CThread& operator=(const CThread&);
CThread(const CThread &);
CThread & operator=(const CThread &);
static void * ThreadWrapper (CThread * _this);
static void * ThreadWrapper(CThread * _this);
CTHREAD_START_ROUTINE m_StartAddress;
void * m_lpThreadParameter;

View File

@ -1,8 +1,8 @@
#include "Trace.h"
#include "StdString.h"
#include "CriticalSection.h"
#include "Thread.h"
#include "Platform.h"
#include "StdString.h"
#include "Thread.h"
#include <map>
#include <vector>
#ifdef _WIN32
@ -26,7 +26,10 @@ public:
CTraceLog()
{
}
~CTraceLog() { CloseTrace(); }
~CTraceLog()
{
CloseTrace();
}
void TraceMessage(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char * Message);
@ -47,7 +50,7 @@ void TraceSetModuleName(uint8_t module, const char * Name)
g_ModuleNames.insert(ModuleNameMap::value_type(module, Name));
}
void WriteTraceFull(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char *format, ...)
void WriteTraceFull(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char * format, ...)
{
va_list args;
va_start(args, format);
@ -142,7 +145,6 @@ void CTraceLog::FlushTrace(void)
{
m_Modules[i]->FlushTrace();
}
}
void CTraceLog::TraceMessage(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char * Message)
@ -202,7 +204,10 @@ const char * TraceModule(uint32_t module)
CTraceFileLog::CTraceFileLog(const char * FileName, bool FlushFile, CLog::LOG_OPEN_MODE eMode, size_t dwMaxFileSize) :
m_FlushFile(FlushFile)
{
enum { MB = 1024 * 1024 };
enum
{
MB = 1024 * 1024
};
m_hLogFile.SetFlush(false);
m_hLogFile.SetTruncateFile(true);
@ -222,7 +227,10 @@ CTraceFileLog::~CTraceFileLog()
void CTraceFileLog::Write(uint32_t module, uint8_t severity, const char * /*file*/, int /*line*/, const char * function, const char * Message)
{
if (!m_hLogFile.IsOpen()) { return; }
if (!m_hLogFile.IsOpen())
{
return;
}
#ifdef _WIN32
SYSTEMTIME sysTime;
@ -230,16 +238,16 @@ void CTraceFileLog::Write(uint32_t module, uint8_t severity, const char * /*file
stdstr_f timestamp("%04d/%02d/%02d %02d:%02d:%02d.%03d %05d,", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds, CThread::GetCurrentThreadId());
#else
time_t ltime;
ltime=time(&ltime);
ltime = time(&ltime);
struct tm result={0};
struct tm result = {0};
localtime_r(&ltime, &result);
struct timeval curTime;
gettimeofday(&curTime, nullptr);
int milliseconds = curTime.tv_usec / 1000;
stdstr_f timestamp("%04d/%02d/%02d %02d:%02d:%02d.%03d %05d,", result.tm_year+1900, result.tm_mon+1, result.tm_mday, result.tm_hour, result.tm_min, result.tm_sec, milliseconds, CThread::GetCurrentThreadId());
stdstr_f timestamp("%04d/%02d/%02d %02d:%02d:%02d.%03d %05d,", result.tm_year + 1900, result.tm_mon + 1, result.tm_mday, result.tm_hour, result.tm_min, result.tm_sec, milliseconds, CThread::GetCurrentThreadId());
#endif
m_hLogFile.Log(timestamp.c_str());

View File

@ -29,7 +29,7 @@ public:
void SetFlushFile(bool bFlushFile);
void Write(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char * Message);
void FlushTrace (void);
void FlushTrace(void);
private:
CLog m_hLogFile;
@ -37,9 +37,17 @@ private:
};
#ifdef _WIN32
#define WriteTrace(m, s, format, ...) if(g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __FUNCTION__, (format), ## __VA_ARGS__); }
#define WriteTrace(m, s, format, ...) \
if (g_ModuleLogLevel[(m)] >= (s)) \
{ \
WriteTraceFull((m), (s), __FILE__, __LINE__, __FUNCTION__, (format), ##__VA_ARGS__); \
}
#else
#define WriteTrace(m, s, format, ...) if(g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __PRETTY_FUNCTION__, (format), ## __VA_ARGS__); }
#define WriteTrace(m, s, format, ...) \
if (g_ModuleLogLevel[(m)] >= (s)) \
{ \
WriteTraceFull((m), (s), __FILE__, __LINE__, __PRETTY_FUNCTION__, (format), ##__VA_ARGS__); \
}
#endif
CTraceModule * TraceAddModule(CTraceModule * TraceModule);
@ -49,7 +57,7 @@ const char * TraceModule(uint32_t module);
void TraceSetModuleName(uint8_t module, const char * Name);
void CloseTrace(void);
void WriteTraceFull(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char *format, ...);
void WriteTraceFull(uint32_t module, uint8_t severity, const char * file, int line, const char * function, const char * format, ...);
void TraceFlushLog(void);
void TraceSetMaxModule(uint32_t MaxModule, uint8_t DefaultSeverity);

View File

@ -3,6 +3,7 @@
#include "path.h"
#ifdef _WIN32
#include <windows.h>
#include <Tlhelp32.h>
#else
#include <time.h>
@ -17,7 +18,8 @@ void pjutil::Sleep(uint32_t timeout)
struct timespec elapsed, tv;
elapsed.tv_sec = timeout / 1000;
elapsed.tv_nsec = (timeout % 1000) * 1000000;
do {
do
{
errno = 0;
tv.tv_sec = elapsed.tv_sec;
tv.tv_nsec = elapsed.tv_nsec;
@ -63,7 +65,7 @@ bool pjutil::TerminatedExistingExe()
break;
}
}
HANDLE hHandle = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, FALSE, lppe.th32ProcessID);
HANDLE hHandle = OpenProcess(SYNCHRONIZE | PROCESS_TERMINATE, FALSE, lppe.th32ProcessID);
if (hHandle != nullptr)
{
if (TerminateProcess(hHandle, 0))

View File

@ -9,6 +9,6 @@ public:
private:
pjutil(void);
pjutil(const pjutil&);
pjutil& operator=(const pjutil&);
pjutil(const pjutil &);
pjutil & operator=(const pjutil &);
};

View File

@ -56,7 +56,7 @@ MD5::~MD5()
// operation, processing another message block, and updating the
// context.
void MD5::update(const uint1 *input, uint4 input_length)
void MD5::update(const uint1 * input, uint4 input_length)
{
uint4 input_index, buffer_index;
uint4 buffer_space;
@ -107,7 +107,7 @@ void MD5::update(const uint1 *input, uint4 input_length)
// MD5 update for files
// Like above, except that it works on files (and uses above as a primitive)
void MD5::update(FILE *file)
void MD5::update(FILE * file)
{
unsigned char update_buffer[1024];
int len;
@ -178,14 +178,14 @@ MD5::MD5(CPath File)
finalize();
}
MD5::MD5(FILE *file)
MD5::MD5(FILE * file)
{
init(); // Must be called by all constructors
update(file);
finalize();
}
MD5::MD5(const unsigned char *input, unsigned int input_length)
MD5::MD5(const unsigned char * input, unsigned int input_length)
{
init(); // Must be called by all constructors
update(input, input_length);
@ -199,17 +199,17 @@ MD5::MD5(const stdstr & string)
finalize();
}
const unsigned char *MD5::raw_digest()
const unsigned char * MD5::raw_digest()
{
if (!finalized)
{
WriteTrace(TraceMD5, TraceError, "Can't get digest if you haven't finalized the digest!");
return ((unsigned char*) "");
return ((unsigned char *)"");
}
return digest;
}
void MD5::get_digest(MD5Digest& extdigest)
void MD5::get_digest(MD5Digest & extdigest)
{
if (!finalized)
{
@ -221,7 +221,7 @@ void MD5::get_digest(MD5Digest& extdigest)
memcpy(extdigest.digest, digest, 16);
}
const char *MD5::hex_digest()
const char * MD5::hex_digest()
{
if (m_hex_digest.length())
{
@ -383,7 +383,7 @@ void MD5::transform(uint1 block[64])
// Encodes input (UINT4) into output (unsigned char). Assumes len is
// a multiple of 4.
void MD5::encode(uint1 *output, uint4 *input, uint4 len)
void MD5::encode(uint1 * output, uint4 * input, uint4 len)
{
unsigned int i, j;
@ -399,7 +399,7 @@ void MD5::encode(uint1 *output, uint4 *input, uint4 len)
// Decodes input (unsigned char) into output (UINT4). Assumes len is
// a multiple of 4.
void MD5::decode(uint4 *output, uint1 *input, uint4 len)
void MD5::decode(uint4 * output, uint1 * input, uint4 len)
{
unsigned int i, j;
@ -411,7 +411,7 @@ void MD5::decode(uint4 *output, uint1 *input, uint4 len)
// Note: Replace "for loop" with standard memcpy if possible
void MD5::memcpy(uint1 *output, uint1 *input, uint4 len)
void MD5::memcpy(uint1 * output, uint1 * input, uint4 len)
{
unsigned int i;
@ -423,7 +423,7 @@ void MD5::memcpy(uint1 *output, uint1 *input, uint4 len)
// Note: Replace "for loop" with standard memset if possible
void MD5::memset(uint1 *output, uint1 value, uint4 len)
void MD5::memset(uint1 * output, uint1 value, uint4 len)
{
unsigned int i;
@ -465,25 +465,25 @@ inline unsigned int MD5::I(uint4 x, uint4 y, uint4 z)
// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
// Rotation is separate from addition to prevent recomputation.
inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
inline void MD5::FF(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{
a += F(b, c, d) + x + ac;
a = rotate_left(a, s) + b;
}
inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
inline void MD5::GG(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{
a += G(b, c, d) + x + ac;
a = rotate_left(a, s) + b;
}
inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
inline void MD5::HH(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{
a += H(b, c, d) + x + ac;
a = rotate_left(a, s) + b;
}
inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
inline void MD5::II(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac)
{
a += I(b, c, d) + x + ac;
a = rotate_left(a, s) + b;

View File

@ -41,19 +41,25 @@ documentation and/or software.
#pragma once
#include <string.h>
#include <stdio.h>
#include <string>
#include <functional>
#include "path.h"
#include "StdString.h"
#include "path.h"
#include <functional>
#include <stdio.h>
#include <string.h>
#include <string>
struct MD5Digest
{
MD5Digest() { Reset(); }
MD5Digest()
{
Reset();
}
unsigned char digest[16];
void Reset() { ::memset(digest, 0, sizeof(digest)); }
void Reset()
{
::memset(digest, 0, sizeof(digest));
}
bool IsClear()
{
int isClear = 0;
@ -79,9 +85,9 @@ struct MD5Digest
}
};
struct MD5Digest_less : std::binary_function < MD5Digest, MD5Digest, bool >
struct MD5Digest_less : std::binary_function<MD5Digest, MD5Digest, bool>
{
bool operator()(const MD5Digest& x, const MD5Digest& y) const
bool operator()(const MD5Digest & x, const MD5Digest & y) const
{
return (memcmp(x.digest, y.digest, sizeof(x.digest)) < 0);
}
@ -93,24 +99,23 @@ public:
// Methods for controlled operation:
MD5(); // Simple initializer
~MD5();
void update(const unsigned char *input, unsigned int input_length);
void update(FILE *file);
void update(const unsigned char * input, unsigned int input_length);
void update(FILE * file);
void finalize();
// Constructors for special circumstances. All these constructors finalize the MD5 context.
MD5(CPath File); // Digest file, finalize
MD5(const unsigned char *string); // Digest string, finalize
MD5(FILE *file); // Digest file, close, finalize
MD5(const unsigned char *input, unsigned int input_length);
MD5(const unsigned char * string); // Digest string, finalize
MD5(FILE * file); // Digest file, close, finalize
MD5(const unsigned char * input, unsigned int input_length);
MD5(const stdstr & string);
// Methods to acquire finalized result
void get_digest(MD5Digest& extdigest); // Digest into a digest structure
const unsigned char *raw_digest(); // Digest as a 16-byte binary array
void get_digest(MD5Digest & extdigest); // Digest into a digest structure
const unsigned char * raw_digest(); // Digest as a 16-byte binary array
const char * hex_digest(); // Digest as a 33-byte ascii-hex string
private:
// First, some types:
typedef unsigned int uint4; // Assumes integer is 4 words long
typedef unsigned short int uint2; // Assumes short integer is 2 words long
@ -126,24 +131,24 @@ private:
// Last, the private methods, mostly static:
void init(); // Called by all constructors
void transform(uint1 *buffer); // Does the real update work. Note that length is implied to be 64.
void transform(uint1 * buffer); // Does the real update work. Note that length is implied to be 64.
static void encode(uint1 *dest, uint4 *src, uint4 length);
static void decode(uint4 *dest, uint1 *src, uint4 length);
static void memcpy(uint1 *dest, uint1 *src, uint4 length);
static void memset(uint1 *start, uint1 val, uint4 length);
static void encode(uint1 * dest, uint4 * src, uint4 length);
static void decode(uint4 * dest, uint1 * src, uint4 length);
static void memcpy(uint1 * dest, uint1 * src, uint4 length);
static void memset(uint1 * start, uint1 val, uint4 length);
static inline uint4 rotate_left(uint4 x, uint4 n);
static inline uint4 F(uint4 x, uint4 y, uint4 z);
static inline uint4 G(uint4 x, uint4 y, uint4 z);
static inline uint4 H(uint4 x, uint4 y, uint4 z);
static inline uint4 I(uint4 x, uint4 y, uint4 z);
static inline void FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x,
static inline void FF(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x,
uint4 s, uint4 ac);
static inline void GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x,
static inline void GG(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x,
uint4 s, uint4 ac);
static inline void HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x,
static inline void HH(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x,
uint4 s, uint4 ac);
static inline void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x,
static inline void II(uint4 & a, uint4 b, uint4 c, uint4 d, uint4 x,
uint4 s, uint4 ac);
};

View File

@ -1,7 +1,7 @@
#include "path.h"
#include "StdString.h"
#include "Trace.h"
#include "TraceModulesCommon.h"
#include "StdString.h"
#ifdef _WIN32
#pragma warning(push)
@ -9,13 +9,14 @@
#pragma warning(disable : 4996) // warning C4091: 'typedef ': ignored on left of 'tagGPFIDL_FLAGS' when no variable is declared
#include <Shlobj.h>
#include <dos.h>
#include <CommDlg.h>
#pragma warning(pop)
#else
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include "Platform.h"
@ -24,9 +25,17 @@
#undef WriteTrace
#ifdef _WIN32
#define WriteTrace(m, s, format, ...) if (g_ModuleLogLevel != nullptr && g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __FUNCTION__, (format), ## __VA_ARGS__); }
#define WriteTrace(m, s, format, ...) \
if (g_ModuleLogLevel != nullptr && g_ModuleLogLevel[(m)] >= (s)) \
{ \
WriteTraceFull((m), (s), __FILE__, __LINE__, __FUNCTION__, (format), ##__VA_ARGS__); \
}
#else
#define WriteTrace(m, s, format, ...) if (g_ModuleLogLevel != nullptr && g_ModuleLogLevel[(m)] >= (s)) { WriteTraceFull((m), (s), __FILE__, __LINE__, __PRETTY_FUNCTION__, (format), ## __VA_ARGS__); }
#define WriteTrace(m, s, format, ...) \
if (g_ModuleLogLevel != nullptr && g_ModuleLogLevel[(m)] >= (s)) \
{ \
WriteTraceFull((m), (s), __FILE__, __LINE__, __PRETTY_FUNCTION__, (format), ##__VA_ARGS__); \
}
#endif
// Constants
@ -89,7 +98,7 @@ inline void CPath::Exit()
#else
if (m_OpenedDir != nullptr)
{
closedir((DIR*)m_OpenedDir);
closedir((DIR *)m_OpenedDir);
m_OpenedDir = nullptr;
}
#endif
@ -107,7 +116,7 @@ CPath::CPath()
// Task: Constructs a path as copy of another
CPath::CPath(const CPath& rPath)
CPath::CPath(const CPath & rPath)
{
Init();
m_strPath = rPath.m_strPath;
@ -137,7 +146,7 @@ CPath::CPath(const char * lpszPath, const char * NameExten)
// Task: Constructs a path and points it to strPath
CPath::CPath(const std::string& strPath)
CPath::CPath(const std::string & strPath)
{
Init();
m_strPath = strPath;
@ -146,26 +155,26 @@ CPath::CPath(const std::string& strPath)
// Task: Constructs a path and points it to strPath
CPath::CPath(const std::string& strPath, const char * NameExten)
CPath::CPath(const std::string & strPath, const char * NameExten)
{
Init();
#ifdef _WIN32
SetDriveDirectory(strPath.c_str());
#else
SetDirectory(strPath.c_str(),true);
SetDirectory(strPath.c_str(), true);
#endif
SetNameExtension(NameExten);
}
// Task: Constructs a path and points it to strPath
CPath::CPath(const std::string& strPath, const std::string& NameExten)
CPath::CPath(const std::string & strPath, const std::string & NameExten)
{
Init();
#ifdef _WIN32
SetDriveDirectory(strPath.c_str());
#else
SetDirectory(strPath.c_str(),true);
SetDirectory(strPath.c_str(), true);
#endif
SetNameExtension(NameExten.c_str());
}
@ -180,7 +189,7 @@ CPath::~CPath()
// Post: Return TRUE if paths are equal
// Task: Check if the two path are the same
bool CPath::operator ==(const CPath& rPath) const
bool CPath::operator==(const CPath & rPath) const
{
// Get fully qualified versions of the paths
std::string FullyQualified1;
@ -196,14 +205,14 @@ bool CPath::operator ==(const CPath& rPath) const
// Post: Return TRUE if paths are different
// Task: Check if the two path are different
bool CPath::operator !=(const CPath& rPath) const
bool CPath::operator!=(const CPath & rPath) const
{
return !(*this == rPath);
}
// Task: Assign a path to another
CPath& CPath::operator =(const CPath& rPath)
CPath & CPath::operator=(const CPath & rPath)
{
if (this != &rPath)
{
@ -215,7 +224,7 @@ CPath& CPath::operator =(const CPath& rPath)
// Post: Return the path, so that assignments can be chained
// Task: Assign a string to a path
CPath& CPath::operator =(const char * lpszPath)
CPath & CPath::operator=(const char * lpszPath)
{
m_strPath = lpszPath ? lpszPath : "";
return *this;
@ -224,7 +233,7 @@ CPath& CPath::operator =(const char * lpszPath)
// Post: Return the path, so that assignments can be chained
// Task: Assign a string to a path
CPath& CPath::operator =(const std::string& strPath)
CPath & CPath::operator=(const std::string & strPath)
{
m_strPath = strPath;
return *this;
@ -249,7 +258,10 @@ CPath::CPath(DIR_CURRENT_DIRECTORY /*sdt*/, const char * NameExten)
// Application's current directory
Init();
CurrentDirectory();
if (NameExten) { SetNameExtension(NameExten); }
if (NameExten)
{
SetNameExtension(NameExten);
}
}
#ifdef _WIN32
@ -258,7 +270,10 @@ CPath::CPath(DIR_MODULE_DIRECTORY /*sdt*/, const char * NameExten)
// The directory where the executable of this app is
Init();
ModuleDirectory();
if (NameExten) { SetNameExtension(NameExten); }
if (NameExten)
{
SetNameExtension(NameExten);
}
}
CPath::CPath(DIR_MODULE_FILE /*sdt*/)
@ -285,14 +300,14 @@ being <= 3 characters, or drives being 1 character.
*/
#ifdef _WIN32
void CPath::GetComponents(std::string* pDrive, std::string* pDirectory, std::string* pName, std::string* pExtension) const
void CPath::GetComponents(std::string * pDrive, std::string * pDirectory, std::string * pName, std::string * pExtension) const
{
WriteTrace(TracePath, TraceDebug, "Start (m_strPath: \"%s\")", m_strPath.c_str());
char buff_drive[_MAX_DRIVE + 1] = { 0 };
char buff_dir[_MAX_DIR + 1] = { 0 };
char buff_name[_MAX_FNAME + 1] = { 0 };
char buff_ext[_MAX_EXT + 1] = { 0 };
char buff_drive[_MAX_DRIVE + 1] = {0};
char buff_dir[_MAX_DIR + 1] = {0};
char buff_name[_MAX_FNAME + 1] = {0};
char buff_ext[_MAX_EXT + 1] = {0};
const char * BasePath = m_strPath.c_str();
const char * DriveDir = strrchr(BasePath, DRIVE_DELIMITER);
@ -348,9 +363,9 @@ void CPath::GetComponents(std::string* pDrive, std::string* pDirectory, std::str
WriteTrace(TracePath, TraceDebug, "Done (dir: \"%s\" name: \"%s\" ext: \"%s\")", buff_dir, buff_name, buff_ext);
}
#else
void CPath::GetComponents(std::string* pDirectory, std::string* pName, std::string* pExtension) const
void CPath::GetComponents(std::string * pDirectory, std::string * pName, std::string * pExtension) const
{
WriteTrace(TracePath, TraceDebug, "Start (m_strPath: \"%s\")",m_strPath.c_str());
WriteTrace(TracePath, TraceDebug, "Start (m_strPath: \"%s\")", m_strPath.c_str());
char buff_dir[260];
char buff_name[260];
@ -361,29 +376,29 @@ void CPath::GetComponents(std::string* pDirectory, std::string* pName, std::stri
memset(buff_ext, 0, sizeof(buff_ext));
const char * BasePath = m_strPath.c_str();
const char * last = strrchr(BasePath,DIRECTORY_DELIMITER);
const char * last = strrchr(BasePath, DIRECTORY_DELIMITER);
if (last != nullptr)
{
int len = sizeof(buff_dir) < (last - BasePath) ? sizeof(buff_dir) : last - BasePath;
if (len > 0)
{
strncpy(buff_dir,BasePath,len);
strncpy(buff_dir, BasePath, len);
}
else
{
buff_dir[0] = DIRECTORY_DELIMITER;
buff_dir[1] = '\0';
}
strncpy(buff_name,last + 1,sizeof(buff_name));
strncpy(buff_name, last + 1, sizeof(buff_name));
}
else
{
strncpy(buff_dir,BasePath,sizeof(buff_dir));
strncpy(buff_dir, BasePath, sizeof(buff_dir));
}
char * ext = strrchr(buff_name,'.');
char * ext = strrchr(buff_name, '.');
if (ext != nullptr)
{
strncpy(buff_ext,ext + 1,sizeof(buff_ext));
strncpy(buff_ext, ext + 1, sizeof(buff_ext));
*ext = '\0';
}
@ -399,14 +414,14 @@ void CPath::GetComponents(std::string* pDirectory, std::string* pName, std::stri
{
*pExtension = buff_ext;
}
WriteTrace(TracePath, TraceDebug, "Done (dir: \"%s\" name: \"%s\" ext: \"%s\")",buff_dir,buff_name,buff_ext);
WriteTrace(TracePath, TraceDebug, "Done (dir: \"%s\" name: \"%s\" ext: \"%s\")", buff_dir, buff_name, buff_ext);
}
#endif
// Task: Get drive and directory from path
#ifdef _WIN32
void CPath::GetDriveDirectory(std::string& rDriveDirectory) const
void CPath::GetDriveDirectory(std::string & rDriveDirectory) const
{
std::string Drive;
std::string Directory;
@ -430,7 +445,7 @@ std::string CPath::GetDriveDirectory(void) const
// Task: Get directory from path
void CPath::GetDirectory(std::string& rDirectory) const
void CPath::GetDirectory(std::string & rDirectory) const
{
#ifdef _WIN32
GetComponents(nullptr, &rDirectory);
@ -448,7 +463,7 @@ std::string CPath::GetDirectory(void) const
// Task: Get filename and extension from path
void CPath::GetNameExtension(std::string& rNameExtension) const
void CPath::GetNameExtension(std::string & rNameExtension) const
{
std::string Name;
std::string Extension;
@ -475,7 +490,7 @@ std::string CPath::GetNameExtension(void) const
// Task: Get filename from path
void CPath::GetName(std::string& rName) const
void CPath::GetName(std::string & rName) const
{
#ifdef _WIN32
GetComponents(nullptr, nullptr, &rName);
@ -493,7 +508,7 @@ std::string CPath::GetName(void) const
// Task: Get file extension from path
void CPath::GetExtension(std::string& rExtension) const
void CPath::GetExtension(std::string & rExtension) const
{
#ifdef _WIN32
GetComponents(nullptr, nullptr, nullptr, &rExtension);
@ -511,7 +526,7 @@ std::string CPath::GetExtension(void) const
// Task: Get current directory
void CPath::GetLastDirectory(std::string& rDirectory) const
void CPath::GetLastDirectory(std::string & rDirectory) const
{
std::string Directory;
@ -538,7 +553,7 @@ std::string CPath::GetLastDirectory(void) const
// Task: Get fully qualified path
void CPath::GetFullyQualified(std::string& rFullyQualified) const
void CPath::GetFullyQualified(std::string & rFullyQualified) const
{
#ifdef _WIN32
char buff_fullname[MAX_PATH];
@ -583,7 +598,7 @@ void CPath::SetComponents(const char * lpszDrive, const char * lpszDirectory, co
memset(buff_fullname, 0, sizeof(buff_fullname));
if (lpszDirectory == nullptr || strlen(lpszDirectory) == 0)
{
static char empty_dir[] = { DIRECTORY_DELIMITER, '\0' };
static char empty_dir[] = {DIRECTORY_DELIMITER, '\0'};
lpszDirectory = empty_dir;
}
@ -599,8 +614,11 @@ void CPath::SetComponents(const char * lpszDirectory, const char * lpszName, con
memset(buff_fullname, 0, sizeof(buff_fullname));
if (lpszDirectory != nullptr && lpszDirectory[0] != '\0')
{
if (lpszDirectory[0] != DIRECTORY_DELIMITER) { buff_fullname[0] = DIRECTORY_DELIMITER; }
strncat(buff_fullname,lpszDirectory,sizeof(buff_fullname) - 1);
if (lpszDirectory[0] != DIRECTORY_DELIMITER)
{
buff_fullname[0] = DIRECTORY_DELIMITER;
}
strncat(buff_fullname, lpszDirectory, sizeof(buff_fullname) - 1);
std::string::size_type nLength = strlen(buff_fullname);
if (buff_fullname[nLength - 1] != DIRECTORY_DELIMITER && nLength < sizeof(buff_fullname))
{
@ -609,15 +627,15 @@ void CPath::SetComponents(const char * lpszDirectory, const char * lpszName, con
}
if (lpszName != nullptr)
{
strncat(buff_fullname,lpszName,sizeof(buff_fullname) - 1);
strncat(buff_fullname, lpszName, sizeof(buff_fullname) - 1);
}
if (lpszExtension != nullptr && lpszExtension[0] != '\0')
{
if (lpszExtension[0] != '.')
{
strncat(buff_fullname,".",sizeof(buff_fullname)-1);
strncat(buff_fullname, ".", sizeof(buff_fullname) - 1);
}
strncat(buff_fullname,lpszExtension,sizeof(buff_fullname)-1);
strncat(buff_fullname, lpszExtension, sizeof(buff_fullname) - 1);
}
buff_fullname[sizeof(buff_fullname) - 1] = 0; // Make sure it is null terminated
m_strPath.erase();
@ -824,7 +842,7 @@ deepest directory (the one we're exiting) in it
Task: Remove deepest subdirectory from path
*/
void CPath::UpDirectory(std::string *pLastDirectory /*= nullptr*/)
void CPath::UpDirectory(std::string * pLastDirectory /*= nullptr*/)
{
std::string Directory;
@ -927,7 +945,7 @@ use CPath::FindFirst() because that routine parses out
bool CPath::DirectoryExists() const
{
WriteTrace(TracePath, TraceDebug, "m_strPath = %s",m_strPath.c_str());
WriteTrace(TracePath, TraceDebug, "m_strPath = %s", m_strPath.c_str());
#ifdef _WIN32
// Create test path
CPath TestPath(m_strPath.c_str());
@ -949,12 +967,12 @@ bool CPath::DirectoryExists() const
std::string PathText;
GetDirectory(PathText);
StripTrailingBackslash(PathText);
WriteTrace(TracePath, TraceDebug, "Checking if directory \"%s\" exists",PathText.c_str());
WriteTrace(TracePath, TraceDebug, "Checking if directory \"%s\" exists", PathText.c_str());
struct stat fileinfo;
bool res = stat(PathText.c_str(), &fileinfo) == 0 && S_ISDIR(fileinfo.st_mode);
#endif
WriteTrace(TracePath, TraceDebug, "Exist = %s",res ? "True" : "False");
WriteTrace(TracePath, TraceDebug, "Exist = %s", res ? "True" : "False");
return res;
}
@ -1053,7 +1071,7 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
{
return false;
}
WriteTrace(TracePath, TraceDebug, "Copy \"%s\" to \"%s\"",m_strPath.c_str(),lpcszTargetFile);
WriteTrace(TracePath, TraceDebug, "Copy \"%s\" to \"%s\"", m_strPath.c_str(), lpcszTargetFile);
#ifdef _WIN32
// Check if the target file exists
CPath TargetFile(lpcszTargetFile);
@ -1079,31 +1097,31 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
#else
bool res = true;
WriteTrace(TracePath, TraceDebug, "Opening \"%s\" for reading",m_strPath.c_str());
WriteTrace(TracePath, TraceDebug, "Opening \"%s\" for reading", m_strPath.c_str());
FILE * infile = fopen(m_strPath.c_str(), "rb");
if(infile == nullptr)
if (infile == nullptr)
{
WriteTrace(TracePath, TraceWarning, "Failed to open m_strPath = %s",m_strPath.c_str());
WriteTrace(TracePath, TraceWarning, "Failed to open m_strPath = %s", m_strPath.c_str());
res = false;
}
else
{
WriteTrace(TracePath, TraceDebug, "Opened \"%s\"",m_strPath.c_str());
WriteTrace(TracePath, TraceDebug, "Opened \"%s\"", m_strPath.c_str());
}
FILE * outfile = nullptr;
if (res)
{
WriteTrace(TracePath, TraceDebug, "Opening \"%s\" for writing",lpcszTargetFile);
WriteTrace(TracePath, TraceDebug, "Opening \"%s\" for writing", lpcszTargetFile);
outfile = fopen(lpcszTargetFile, "wb");
if (outfile == nullptr)
{
WriteTrace(TracePath, TraceWarning, "Failed to open m_strPath = %s errno=%d",lpcszTargetFile, errno);
WriteTrace(TracePath, TraceWarning, "Failed to open m_strPath = %s errno=%d", lpcszTargetFile, errno);
res = false;
}
else
{
WriteTrace(TracePath, TraceDebug, "Opened \"%s\"",lpcszTargetFile);
WriteTrace(TracePath, TraceDebug, "Opened \"%s\"", lpcszTargetFile);
}
}
@ -1144,7 +1162,7 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
}
if (res)
{
if (fchmod(fileno(outfile),ts.st_mode) != 0)
if (fchmod(fileno(outfile), ts.st_mode) != 0)
{
WriteTrace(TracePath, TraceWarning, "fchmod failed on %s, errno = %X", lpcszTargetFile, errno);
res = false;
@ -1158,7 +1176,7 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
{
fclose(outfile);
}
WriteTrace(TracePath, TraceDebug, "Done, res: %s",res ? "true" : "false");
WriteTrace(TracePath, TraceDebug, "Done, res: %s", res ? "true" : "false");
return res;
#endif
}
@ -1334,20 +1352,20 @@ bool CPath::FindNext()
}
}
#else
dirent* pEntry;
while ((pEntry = readdir((DIR*)m_OpenedDir)))
dirent * pEntry;
while ((pEntry = readdir((DIR *)m_OpenedDir)))
{
uint32_t dwFileAttributes = pEntry->d_type == DT_DIR ? FIND_ATTRIBUTE_SUBDIR : FIND_ATTRIBUTE_FILES;
WriteTrace(TracePath, TraceVerbose, "m_dwFindFileAttributes = %X dwFileAttributes = %X AttributesMatch: %s",m_dwFindFileAttributes, dwFileAttributes, AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) ? "true" : "false");
WriteTrace(TracePath, TraceVerbose, "m_dwFindFileAttributes = %X dwFileAttributes = %X AttributesMatch: %s", m_dwFindFileAttributes, dwFileAttributes, AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) ? "true" : "false");
// Compare candidate to attributes, and filter out the "." and ".." folders
if (!AttributesMatch(m_dwFindFileAttributes, dwFileAttributes) ||
strcmp(pEntry->d_name,".") == 0 ||
strcmp(pEntry->d_name,"..") == 0 ||
!wildcmp(m_FindWildcard.c_str(),pEntry->d_name))
strcmp(pEntry->d_name, ".") == 0 ||
strcmp(pEntry->d_name, "..") == 0 ||
!wildcmp(m_FindWildcard.c_str(), pEntry->d_name))
{
WriteTrace(TracePath, TraceVerbose, "Continue, d_name = %s",pEntry->d_name);
WriteTrace(TracePath, TraceVerbose, "Continue, d_name = %s", pEntry->d_name);
continue;
}
if ((FIND_ATTRIBUTE_SUBDIR & dwFileAttributes) == FIND_ATTRIBUTE_SUBDIR)
@ -1457,7 +1475,7 @@ void CPath::NormalizePath(CPath BaseDir)
bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
{
WriteTrace(TracePath, TraceDebug, "m_strPath = %s bCreateIntermediates = %s",m_strPath.c_str(),bCreateIntermediates ? "true" : "false");
WriteTrace(TracePath, TraceDebug, "m_strPath = %s bCreateIntermediates = %s", m_strPath.c_str(), bCreateIntermediates ? "true" : "false");
std::string PathText;
bool bSuccess;
@ -1470,16 +1488,16 @@ bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
#ifdef _WIN32
GetDriveDirectory(PathText);
StripTrailingBackslash(PathText);
WriteTrace(TracePath, TraceDebug, "Create %s",PathText.c_str());
WriteTrace(TracePath, TraceDebug, "Create %s", PathText.c_str());
bSuccess = ::CreateDirectoryA(PathText.c_str(), nullptr) != 0;
#else
GetDirectory(PathText);
StripTrailingBackslash(PathText);
WriteTrace(TracePath, TraceDebug, "Create %s",PathText.c_str());
WriteTrace(TracePath, TraceDebug, "Create %s", PathText.c_str());
bSuccess = mkdir(PathText.c_str(), S_IRWXU) == 0;
if (!bSuccess)
{
WriteTrace(TracePath, TraceWarning, "Failed to create \"%s\" errno: %d",PathText.c_str(), errno);
WriteTrace(TracePath, TraceWarning, "Failed to create \"%s\" errno: %d", PathText.c_str(), errno);
}
#endif
if (!bSuccess && bCreateIntermediates)
@ -1496,7 +1514,7 @@ bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
return SubPath.DirectoryCreate() ? DirectoryCreate(false) : false;
}
WriteTrace(TracePath, TraceDebug, "res = %s",bSuccess ? "true" : "false");
WriteTrace(TracePath, TraceDebug, "res = %s", bSuccess ? "true" : "false");
return bSuccess;
}
@ -1504,7 +1522,7 @@ bool CPath::DirectoryCreate(bool bCreateIntermediates /*= TRUE*/)
// Task: Remove first character (if any) if it's chLeading
void CPath::cleanPathString(std::string& rDirectory) const
void CPath::cleanPathString(std::string & rDirectory) const
{
std::string::size_type pos = rDirectory.find(DIRECTORY_DELIMITER2);
while (pos != std::string::npos)
@ -1526,7 +1544,7 @@ void CPath::cleanPathString(std::string& rDirectory) const
}
}
void CPath::StripLeadingChar(std::string& rText, char chLeading) const
void CPath::StripLeadingChar(std::string & rText, char chLeading) const
{
std::string::size_type nLength = rText.length();
if (nLength == 0)
@ -1538,7 +1556,7 @@ void CPath::StripLeadingChar(std::string& rText, char chLeading) const
// Task: Remove first character if '\'
void CPath::StripLeadingBackslash(std::string& Directory) const
void CPath::StripLeadingBackslash(std::string & Directory) const
{
std::string::size_type nLength = Directory.length();
@ -1552,7 +1570,7 @@ void CPath::StripLeadingBackslash(std::string& Directory) const
// Task: Remove last character (if any) if it's chTrailing
void CPath::StripTrailingChar(std::string& rText, char chTrailing) const
void CPath::StripTrailingChar(std::string & rText, char chTrailing) const
{
std::string::size_type nLength = rText.length();
if (nLength == 0)
@ -1564,7 +1582,7 @@ void CPath::StripTrailingChar(std::string& rText, char chTrailing) const
// Task: Remove last character if '\'
void CPath::StripTrailingBackslash(std::string& rDirectory) const
void CPath::StripTrailingBackslash(std::string & rDirectory) const
{
for (;;)
{
@ -1585,7 +1603,7 @@ void CPath::StripTrailingBackslash(std::string& rDirectory) const
// Task: Add a backslash to the end of the directory if there is not already one there
void CPath::EnsureTrailingBackslash(std::string& Directory) const
void CPath::EnsureTrailingBackslash(std::string & Directory) const
{
std::string::size_type nLength = Directory.length();
@ -1606,7 +1624,7 @@ void CPath::EnsureLeadingBackslash(std::string & Directory) const
}
#ifndef _WIN32
bool CPath::wildcmp(const char *wild, const char *string)
bool CPath::wildcmp(const char * wild, const char * string)
{
const char *cp = nullptr, *mp = nullptr;
@ -1629,7 +1647,7 @@ bool CPath::wildcmp(const char *wild, const char *string)
return 1;
}
mp = wild;
cp = string+1;
cp = string + 1;
}
else if ((*wild == *string) || (*wild == '?'))
{

View File

@ -1,16 +1,24 @@
#pragma once
#include <string>
#include <stdint.h>
#include <string>
class CPath
{
// Enums
public:
enum DIR_CURRENT_DIRECTORY { CURRENT_DIRECTORY = 1 };
enum DIR_CURRENT_DIRECTORY
{
CURRENT_DIRECTORY = 1
};
#ifdef _WIN32
enum DIR_MODULE_DIRECTORY { MODULE_DIRECTORY = 2 };
enum DIR_MODULE_FILE { MODULE_FILE = 3 };
enum DIR_MODULE_DIRECTORY
{
MODULE_DIRECTORY = 2
};
enum DIR_MODULE_FILE
{
MODULE_FILE = 3
};
#endif
enum
@ -37,12 +45,12 @@ public:
// Construction / destruction
CPath();
CPath(const CPath& rPath);
CPath(const CPath & rPath);
CPath(const char * lpszPath);
CPath(const char * lpszPath, const char * NameExten);
CPath(const std::string& strPath);
CPath(const std::string& strPath, const char * NameExten);
CPath(const std::string& strPath, const std::string& NameExten);
CPath(const std::string & strPath);
CPath(const std::string & strPath, const char * NameExten);
CPath(const std::string & strPath, const std::string & NameExten);
CPath(DIR_CURRENT_DIRECTORY sdt, const char * NameExten = nullptr);
#ifdef _WIN32
@ -52,37 +60,43 @@ public:
virtual ~CPath();
// Operators
CPath& operator = (const CPath& rPath);
CPath& operator = (const char * lpszPath);
CPath& operator = (const std::string & strPath);
bool operator == (const CPath& rPath) const;
bool operator != (const CPath& rPath) const;
CPath & operator=(const CPath & rPath);
CPath & operator=(const char * lpszPath);
CPath & operator=(const std::string & strPath);
bool operator==(const CPath & rPath) const;
bool operator!=(const CPath & rPath) const;
operator const char *() const;
operator const std::string &() { return m_strPath; }
operator const std::string &()
{
return m_strPath;
}
// Get path components
#ifdef _WIN32
void GetDriveDirectory(std::string & rDriveDirectory) const;
std::string GetDriveDirectory(void) const;
#endif
void GetDirectory(std::string& rDirectory) const;
void GetDirectory(std::string & rDirectory) const;
std::string GetDirectory(void) const;
void GetName(std::string& rName) const;
void GetName(std::string & rName) const;
std::string GetName(void) const;
void GetNameExtension(std::string& rNameExtension) const;
void GetNameExtension(std::string & rNameExtension) const;
std::string GetNameExtension(void) const;
void GetExtension(std::string& rExtension) const;
void GetExtension(std::string & rExtension) const;
std::string GetExtension(void) const;
void GetLastDirectory(std::string& rDirectory) const;
void GetLastDirectory(std::string & rDirectory) const;
std::string GetLastDirectory(void) const;
void GetFullyQualified(std::string& rFullyQualified) const;
void GetFullyQualified(std::string & rFullyQualified) const;
#ifdef _WIN32
void GetComponents(std::string* pDrive = nullptr, std::string* pDirectory = nullptr, std::string* pName = nullptr, std::string* pExtension = nullptr) const;
void GetComponents(std::string * pDrive = nullptr, std::string * pDirectory = nullptr, std::string * pName = nullptr, std::string * pExtension = nullptr) const;
#else
void GetComponents(std::string* pDirectory = nullptr, std::string* pName = nullptr, std::string* pExtension = nullptr) const;
void GetComponents(std::string * pDirectory = nullptr, std::string * pName = nullptr, std::string * pExtension = nullptr) const;
#endif
// Get other state
bool IsEmpty() const { return m_strPath.empty(); }
bool IsEmpty() const
{
return m_strPath.empty();
}
bool IsRelative() const;
// Set path components
@ -97,14 +111,17 @@ public:
void SetExtension(const char * lpszExtension);
void SetExtension(int iExtension);
void AppendDirectory(const char * lpszSubDirectory);
void UpDirectory(std::string* pLastDirectory = nullptr);
void UpDirectory(std::string * pLastDirectory = nullptr);
#ifdef _WIN32
void SetComponents(const char * lpszDrive, const char * lpszDirectory, const char * lpszName, const char * lpszExtension);
#else
void SetComponents(const char * lpszDirectory, const char * lpszName, const char * lpszExtension);
#endif
// Set whole path
void Empty() { m_strPath.erase(); }
void Empty()
{
m_strPath.erase();
}
void CurrentDirectory();
#ifdef _WIN32
void Module();
@ -118,7 +135,10 @@ public:
bool DirectoryExists() const;
// File information
bool IsFile() const { return !IsDirectory(); }
bool IsFile() const
{
return !IsDirectory();
}
bool Exists() const;
#ifdef _WIN32
bool SelectFile(void * hwndOwner, const char * InitialDir, const char * FileFilter, bool FileMustExist);
@ -151,14 +171,14 @@ private:
bool AttributesMatch(uint32_t dwTargetAttributes, uint32_t dwFileAttributes);
void cleanPathString(std::string& rDirectory) const;
void StripLeadingChar(std::string& rText, char chLeading) const;
void StripLeadingBackslash(std::string& Directory) const;
void StripTrailingChar(std::string& rText, char chTrailing) const;
void StripTrailingBackslash(std::string& rDirectory) const;
void EnsureTrailingBackslash(std::string& Directory) const;
void EnsureLeadingBackslash(std::string& Directory) const;
void cleanPathString(std::string & rDirectory) const;
void StripLeadingChar(std::string & rText, char chLeading) const;
void StripLeadingBackslash(std::string & Directory) const;
void StripTrailingChar(std::string & rText, char chTrailing) const;
void StripTrailingBackslash(std::string & rDirectory) const;
void EnsureTrailingBackslash(std::string & Directory) const;
void EnsureLeadingBackslash(std::string & Directory) const;
#ifndef _WIN32
bool wildcmp(const char *wild, const char *string);
bool wildcmp(const char * wild, const char * string);
#endif
};