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

@ -3,32 +3,34 @@
class CriticalSection
{
public:
CriticalSection();
~CriticalSection(void);
CriticalSection();
~CriticalSection(void);
void enter(void);
void leave(void);
void enter(void);
void leave(void);
private:
CriticalSection(const CriticalSection&);
CriticalSection& operator=(const CriticalSection&);
CriticalSection(const CriticalSection &);
CriticalSection & operator=(const CriticalSection &);
void * m_cs;
void * m_cs;
};
class CGuard
{
public:
CGuard(CriticalSection& sectionName) : m_cs(sectionName)
{
m_cs.enter();
}
~CGuard()
{
m_cs.leave();
}
CGuard(CriticalSection & sectionName) :
m_cs(sectionName)
{
m_cs.enter();
}
~CGuard()
{
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

@ -13,7 +13,7 @@
#if defined(_MSC_VER)
#include <crtdbg.h>
#else
#define _ASSERTE(expr) ((void)0)
#define _ASSERTE(expr) ((void)0)
#endif
CFile::CFile() :
@ -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,11 +240,11 @@ 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)
{
return true; // Avoid Win32 "null-write" option
return true; // Avoid Win32 "null-write" option
}
#ifdef USE_WINDOWS_API
@ -259,11 +268,11 @@ 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)
{
return 0; // Avoid Win32 "null-read"
return 0; // Avoid Win32 "null-read"
}
#ifdef USE_WINDOWS_API
@ -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

@ -20,21 +20,21 @@ public:
};
enum SeekPosition
{
begin = 0x0,
current = 0x1,
end = 0x2
};
{
begin = 0x0,
current = 0x1,
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);
@ -125,7 +128,7 @@ public:
}
protected:
CFileStorage m_FileObject;
CFileStorage m_FileObject;
};
typedef CIniFileT<CFile> CIniFile;

View File

@ -1,178 +1,196 @@
#include "Log.h"
#include "path.h"
#include "Platform.h"
#include <stdio.h>
#include "path.h"
#include <stdarg.h>
#include <stdio.h>
CLog::CLog (void ) :
m_FlushOnWrite(false),
m_TruncateFileLog(true),
m_MaxFileSize(MAX_FILE_SIZE),
m_FileChangeSize(0),
CLog::CLog(void) :
m_FlushOnWrite(false),
m_TruncateFileLog(true),
m_MaxFileSize(MAX_FILE_SIZE),
m_FileChangeSize(0),
m_FileSize(0)
{
}
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)
{
return false;
}
if (FileName == nullptr)
{
return false;
}
CPath File(FileName);
if (m_hLogFile.IsOpen())
{
m_hLogFile.Close();
}
CPath File(FileName);
if (m_hLogFile.IsOpen())
{
m_hLogFile.Close();
}
uint32_t nOpenFlags = CFile::modeReadWrite | CFile::modeCreate;
if (mode == Log_Append) { nOpenFlags |= CFile::modeNoTruncate; }
uint32_t nOpenFlags = CFile::modeReadWrite | CFile::modeCreate;
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);
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_FileSize = mode == Log_Append ? (uint32_t)m_hLogFile.GetLength() : 0;
return true;
return true;
}
void CLog::Close ( void )
void CLog::Close(void)
{
if (m_hLogFile.IsOpen())
{
m_hLogFile.Close();
}
if (m_hLogFile.IsOpen())
{
m_hLogFile.Close();
}
}
void CLog::LogF(const char * Message, ...)
void CLog::LogF(const char * Message, ...)
{
va_list ap;
va_start( ap, Message );
LogArgs(Message,ap);
va_end( ap );
va_list 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
{
size_t nlen = _vscprintf(Message, args) + 1;
char * Msg = (char *)alloca(nlen * sizeof(char));
Msg[nlen - 1] = 0;
if (Msg != nullptr)
{
vsprintf(Msg, Message, args);
Log(Msg);
}
}
catch(...)
{
Log("Invalid message format");
}
try
{
size_t nlen = _vscprintf(Message, args) + 1;
char * Msg = (char *)alloca(nlen * sizeof(char));
Msg[nlen - 1] = 0;
if (Msg != nullptr)
{
vsprintf(Msg, Message, args);
Log(Msg);
}
}
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)
{
m_hLogFile.Flush();
}
m_hLogFile.Write(Message, message_len);
if (m_FlushOnWrite)
{
m_hLogFile.Flush();
}
m_FileSize += message_len;
if (m_TruncateFileLog && m_FileSize > m_MaxFileSize)
{
// Check file size
if (m_TruncateFileLog && m_FileSize > m_MaxFileSize)
{
// Check file size
m_FileSize = (uint32_t)m_hLogFile.GetLength();
// If larger then maximum size then
if (m_FileSize > m_MaxFileSize)
{
if (!m_FlushOnWrite)
{
m_hLogFile.Flush();
// If larger then maximum size then
if (m_FileSize > m_MaxFileSize)
{
if (!m_FlushOnWrite)
{
m_hLogFile.Flush();
m_FileSize = (uint32_t)m_hLogFile.GetLength();
}
}
uint32_t end = (uint32_t)m_hLogFile.SeekToEnd();
uint32_t end = (uint32_t)m_hLogFile.SeekToEnd();
// Move to reduce size
m_hLogFile.Seek((end - m_MaxFileSize) + m_FileChangeSize,CFile::begin);
// Move to reduce size
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));
if (dwRead == 0)
{
break;
}
// Find next end of line
uint32_t NextEnter = 0, dwRead = 0;
do
{
uint8_t Data[300];
dwRead = m_hLogFile.Read(Data, sizeof(Data));
if (dwRead == 0)
{
break;
}
for (int i = 0; i < sizeof(Data); i++)
{
if (Data[i] == '\n')
{
NextEnter += (i + 1);
dwRead = 0;
break;
}
}
NextEnter += dwRead;
} while(dwRead != 0);
for (int i = 0; i < sizeof(Data); i++)
{
if (Data[i] == '\n')
{
NextEnter += (i + 1);
dwRead = 0;
break;
}
}
NextEnter += dwRead;
} 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 };
unsigned char Data[fIS_MvSize + 1];
// 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
};
unsigned char Data[fIS_MvSize + 1];
SizeToRead = end - ReadPos;
if (SizeToRead > fIS_MvSize) { SizeToRead = fIS_MvSize; }
SizeToRead = end - ReadPos;
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))
{
//BreakPoint(__FILE__,__LINE__);
break;
}
if (!m_hLogFile.Write(Data, dwRead))
{
//BreakPoint(__FILE__,__LINE__);
break;
}
ReadPos += dwRead;
WritePos += dwRead;
} while (SizeToRead > 0);
ReadPos += dwRead;
WritePos += dwRead;
} while (SizeToRead > 0);
// Clean up
m_hLogFile.SetEndOfFile();
m_hLogFile.Flush();
// Clean up
m_hLogFile.SetEndOfFile();
m_hLogFile.Flush();
m_FileSize = (uint32_t)m_hLogFile.GetLength();
} // end if
}
} // end if
}
}
bool CLog::Empty(void)
bool CLog::Empty(void)
{
if (!m_hLogFile.IsOpen()) { return true; }
if (m_hLogFile.GetLength() == 0)
{
return true;
}
return false;
if (!m_hLogFile.IsOpen())
{
return true;
}
if (m_hLogFile.GetLength() == 0)
{
return true;
}
return false;
}

View File

@ -1,19 +1,26 @@
#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,16 +36,31 @@ 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;
std::string m_FileName;

View File

@ -10,9 +10,9 @@
static bool InInit = false;
class CMemList
class CMemList
{
typedef struct
typedef struct
{
char File[300];
int line;
@ -26,7 +26,7 @@ class CMemList
public:
CMemList();
~CMemList();
void removeItem(void * ptr);
void RecordAddItem(void * ptr, size_t size, const char * filename, int line);
void DumpItems(void);
@ -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)
@ -149,7 +149,7 @@ void CMemList::DumpItems(void)
SetFilePointer(hLogFile, 0, nullptr, FILE_BEGIN);
DWORD dwWritten = 0;
char Msg[800];
char Msg[800];
_snprintf(Msg, sizeof(Msg), "Order, Source File, Line Number, Mem Size\r\n");
WriteFile(hLogFile, Msg, (DWORD)strlen(Msg), &dwWritten, nullptr);
@ -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

@ -1,4 +1,4 @@
#pragma once
#pragma once
#if (defined(_MSC_VER) && _DEBUG)
#define MEM_LEAK_TEST
@ -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;
@ -24,22 +24,22 @@ public:
stdstr(const stdstr & str);
stdstr(const char * str);
strvector Tokenize(char delimiter) const;
strvector Tokenize(const char * delimiter) const;
void Format(const char * strFormat, ...);
stdstr& ToLower(void);
stdstr& ToUpper(void);
strvector Tokenize(char delimiter) const;
strvector Tokenize(const char * delimiter) const;
void Format(const char * strFormat, ...);
stdstr & ToLower(void);
stdstr & ToUpper(void);
void Replace(const char search, const char replace);
void Replace(const char * search, const char replace);
void Replace(const std::string & search, const std::string & replace);
void Replace(const char search, const char replace);
void Replace(const char * search, const char replace);
void Replace(const std::string & search, const std::string & replace);
stdstr & Trim(const char * chars2remove = "\t ");
stdstr & TrimLeft(const char * chars2remove = "\t ");
stdstr & TrimRight(const char * chars2remove = "\t ");
stdstr & Trim(const char * chars2remove = "\t ");
stdstr & TrimLeft(const char * chars2remove = "\t ");
stdstr & TrimRight(const char * chars2remove = "\t ");
#ifdef _WIN32
stdstr & FromUTF16(const wchar_t * UTF16Source, bool * bSuccess = nullptr);
stdstr & FromUTF16(const wchar_t * UTF16Source, bool * bSuccess = nullptr);
std::wstring ToUTF16(unsigned int CodePage = CODEPAGE_UTF8, bool * bSuccess = nullptr) const;
#endif
@ -49,14 +49,14 @@ public:
class stdstr_f : public stdstr
{
public:
stdstr_f(const char * strFormat, ...);
stdstr_f(const char * strFormat, ...);
};
#ifdef _WIN32
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

@ -1,31 +1,34 @@
#pragma once
#include <stdint.h>
class CThread
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);
static uint32_t GetCurrentThreadId(void);
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;
@ -166,7 +166,7 @@ void MD5::finalize()
MD5::MD5(CPath File)
{
init(); // Must be called by all constructors
init(); // Must be called by all constructors
if (File.Exists())
{
FILE * fp = fopen((const char *)File, "rb");
@ -178,38 +178,38 @@ MD5::MD5(CPath File)
finalize();
}
MD5::MD5(FILE *file)
MD5::MD5(FILE * file)
{
init(); // Must be called by all constructors
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
init(); // Must be called by all constructors
update(input, input_length);
finalize();
}
MD5::MD5(const stdstr & string)
{
init(); // Must be called by all constructors
init(); // Must be called by all constructors
update((const unsigned char *)string.c_str(), (uint4)string.length());
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())
{
@ -250,7 +250,7 @@ const char *MD5::hex_digest()
void MD5::init()
{
finalized = 0; // We just started!
finalized = 0; // We just started!
// Nothing counted, so count=0
count[0] = 0;
@ -300,16 +300,16 @@ void MD5::transform(uint1 block[64])
//ATLASSERT(!finalized); // Not just a user error, since the method is private
// Round 1
FF(a, b, c, d, x[0], S11, 0xd76aa478); // 1
FF(d, a, b, c, x[1], S12, 0xe8c7b756); // 2
FF(c, d, a, b, x[2], S13, 0x242070db); // 3
FF(b, c, d, a, x[3], S14, 0xc1bdceee); // 4
FF(a, b, c, d, x[4], S11, 0xf57c0faf); // 5
FF(d, a, b, c, x[5], S12, 0x4787c62a); // 6
FF(c, d, a, b, x[6], S13, 0xa8304613); // 7
FF(b, c, d, a, x[7], S14, 0xfd469501); // 8
FF(a, b, c, d, x[8], S11, 0x698098d8); // 9
FF(d, a, b, c, x[9], S12, 0x8b44f7af); // 10
FF(a, b, c, d, x[0], S11, 0xd76aa478); // 1
FF(d, a, b, c, x[1], S12, 0xe8c7b756); // 2
FF(c, d, a, b, x[2], S13, 0x242070db); // 3
FF(b, c, d, a, x[3], S14, 0xc1bdceee); // 4
FF(a, b, c, d, x[4], S11, 0xf57c0faf); // 5
FF(d, a, b, c, x[5], S12, 0x4787c62a); // 6
FF(c, d, a, b, x[6], S13, 0xa8304613); // 7
FF(b, c, d, a, x[7], S14, 0xfd469501); // 8
FF(a, b, c, d, x[8], S11, 0x698098d8); // 9
FF(d, a, b, c, x[9], S12, 0x8b44f7af); // 10
FF(c, d, a, b, x[10], S13, 0xffff5bb1); // 11
FF(b, c, d, a, x[11], S14, 0x895cd7be); // 12
FF(a, b, c, d, x[12], S11, 0x6b901122); // 13
@ -318,58 +318,58 @@ void MD5::transform(uint1 block[64])
FF(b, c, d, a, x[15], S14, 0x49b40821); // 16
// Round 2
GG(a, b, c, d, x[1], S21, 0xf61e2562); // 17
GG(d, a, b, c, x[6], S22, 0xc040b340); // 18
GG(a, b, c, d, x[1], S21, 0xf61e2562); // 17
GG(d, a, b, c, x[6], S22, 0xc040b340); // 18
GG(c, d, a, b, x[11], S23, 0x265e5a51); // 19
GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); // 20
GG(a, b, c, d, x[5], S21, 0xd62f105d); // 21
GG(d, a, b, c, x[10], S22, 0x2441453); // 22
GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); // 20
GG(a, b, c, d, x[5], S21, 0xd62f105d); // 21
GG(d, a, b, c, x[10], S22, 0x2441453); // 22
GG(c, d, a, b, x[15], S23, 0xd8a1e681); // 23
GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); // 24
GG(a, b, c, d, x[9], S21, 0x21e1cde6); // 25
GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); // 24
GG(a, b, c, d, x[9], S21, 0x21e1cde6); // 25
GG(d, a, b, c, x[14], S22, 0xc33707d6); // 26
GG(c, d, a, b, x[3], S23, 0xf4d50d87); // 27
GG(b, c, d, a, x[8], S24, 0x455a14ed); // 28
GG(c, d, a, b, x[3], S23, 0xf4d50d87); // 27
GG(b, c, d, a, x[8], S24, 0x455a14ed); // 28
GG(a, b, c, d, x[13], S21, 0xa9e3e905); // 29
GG(d, a, b, c, x[2], S22, 0xfcefa3f8); // 30
GG(c, d, a, b, x[7], S23, 0x676f02d9); // 31
GG(d, a, b, c, x[2], S22, 0xfcefa3f8); // 30
GG(c, d, a, b, x[7], S23, 0x676f02d9); // 31
GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); // 32
// Round 3
HH(a, b, c, d, x[5], S31, 0xfffa3942); // 33
HH(d, a, b, c, x[8], S32, 0x8771f681); // 34
HH(a, b, c, d, x[5], S31, 0xfffa3942); // 33
HH(d, a, b, c, x[8], S32, 0x8771f681); // 34
HH(c, d, a, b, x[11], S33, 0x6d9d6122); // 35
HH(b, c, d, a, x[14], S34, 0xfde5380c); // 36
HH(a, b, c, d, x[1], S31, 0xa4beea44); // 37
HH(d, a, b, c, x[4], S32, 0x4bdecfa9); // 38
HH(c, d, a, b, x[7], S33, 0xf6bb4b60); // 39
HH(a, b, c, d, x[1], S31, 0xa4beea44); // 37
HH(d, a, b, c, x[4], S32, 0x4bdecfa9); // 38
HH(c, d, a, b, x[7], S33, 0xf6bb4b60); // 39
HH(b, c, d, a, x[10], S34, 0xbebfbc70); // 40
HH(a, b, c, d, x[13], S31, 0x289b7ec6); // 41
HH(d, a, b, c, x[0], S32, 0xeaa127fa); // 42
HH(c, d, a, b, x[3], S33, 0xd4ef3085); // 43
HH(b, c, d, a, x[6], S34, 0x4881d05); // 44
HH(a, b, c, d, x[9], S31, 0xd9d4d039); // 45
HH(d, a, b, c, x[0], S32, 0xeaa127fa); // 42
HH(c, d, a, b, x[3], S33, 0xd4ef3085); // 43
HH(b, c, d, a, x[6], S34, 0x4881d05); // 44
HH(a, b, c, d, x[9], S31, 0xd9d4d039); // 45
HH(d, a, b, c, x[12], S32, 0xe6db99e5); // 46
HH(c, d, a, b, x[15], S33, 0x1fa27cf8); // 47
HH(b, c, d, a, x[2], S34, 0xc4ac5665); // 48
HH(b, c, d, a, x[2], S34, 0xc4ac5665); // 48
// Round 4
II(a, b, c, d, x[0], S41, 0xf4292244); // 49
II(d, a, b, c, x[7], S42, 0x432aff97); // 50
II(a, b, c, d, x[0], S41, 0xf4292244); // 49
II(d, a, b, c, x[7], S42, 0x432aff97); // 50
II(c, d, a, b, x[14], S43, 0xab9423a7); // 51
II(b, c, d, a, x[5], S44, 0xfc93a039); // 52
II(b, c, d, a, x[5], S44, 0xfc93a039); // 52
II(a, b, c, d, x[12], S41, 0x655b59c3); // 53
II(d, a, b, c, x[3], S42, 0x8f0ccc92); // 54
II(d, a, b, c, x[3], S42, 0x8f0ccc92); // 54
II(c, d, a, b, x[10], S43, 0xffeff47d); // 55
II(b, c, d, a, x[1], S44, 0x85845dd1); // 56
II(a, b, c, d, x[8], S41, 0x6fa87e4f); // 57
II(b, c, d, a, x[1], S44, 0x85845dd1); // 56
II(a, b, c, d, x[8], S41, 0x6fa87e4f); // 57
II(d, a, b, c, x[15], S42, 0xfe2ce6e0); // 58
II(c, d, a, b, x[6], S43, 0xa3014314); // 59
II(c, d, a, b, x[6], S43, 0xa3014314); // 59
II(b, c, d, a, x[13], S44, 0x4e0811a1); // 60
II(a, b, c, d, x[4], S41, 0xf7537e82); // 61
II(a, b, c, d, x[4], S41, 0xf7537e82); // 61
II(d, a, b, c, x[11], S42, 0xbd3af235); // 62
II(c, d, a, b, x[2], S43, 0x2ad7d2bb); // 63
II(b, c, d, a, x[9], S44, 0xeb86d391); // 64
II(c, d, a, b, x[2], S43, 0x2ad7d2bb); // 63
II(b, c, d, a, x[9], S44, 0xeb86d391); // 64
state[0] += a;
state[1] += b;
@ -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);
}
@ -91,59 +97,58 @@ class MD5
{
public:
// Methods for controlled operation:
MD5(); // Simple initializer
MD5(); // Simple initializer
~MD5();
void update(const unsigned char *input, unsigned int input_length);
void update(FILE *file);
void finalize();
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(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 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
const char * hex_digest(); // Digest as a 33-byte ascii-hex string
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 int uint4; // Assumes integer is 4 words long
typedef unsigned short int uint2; // Assumes short integer is 2 words long
typedef unsigned char uint1; // Assumes char is 1 word long
typedef unsigned char uint1; // Assumes char is 1 word long
// Next, the private data:
uint4 state[4];
uint4 count[2]; // Number of *bits*, mod 2^64
uint1 buffer[64]; // Input buffer
uint4 count[2]; // Number of *bits*, mod 2^64
uint1 buffer[64]; // Input buffer
uint1 digest[16];
uint1 finalized;
stdstr m_hex_digest;
// 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 init(); // Called by all constructors
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,
uint4 s, uint4 ac);
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,
uint4 s, uint4 ac);
static inline void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x,
uint4 s, uint4 ac);
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,
uint4 s, uint4 ac);
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,
uint4 s, uint4 ac);
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];
@ -560,15 +575,15 @@ bool CPath::IsRelative() const
{
return false;
}
if (m_strPath.length() > 2 && m_strPath[0] == DIRECTORY_DELIMITER && m_strPath[1] == DIRECTORY_DELIMITER)
{
return false;
}
if (m_strPath.length() > 2 && m_strPath[0] == DIRECTORY_DELIMITER && m_strPath[1] == DIRECTORY_DELIMITER)
{
return false;
}
#else
if (m_strPath.length() > 1 && m_strPath[0] == DIRECTORY_DELIMITER)
{
return false;
}
if (m_strPath.length() > 1 && m_strPath[0] == DIRECTORY_DELIMITER)
{
return false;
}
#endif
return true;
}
@ -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,25 +614,28 @@ 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))
if (buff_fullname[nLength - 1] != DIRECTORY_DELIMITER && nLength < sizeof(buff_fullname))
{
buff_fullname[nLength] = DIRECTORY_DELIMITER;
}
}
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();
@ -631,9 +649,9 @@ void CPath::SetComponents(const char * lpszDirectory, const char * lpszName, con
void CPath::SetDrive(char chDrive)
{
stdstr_f Drive("%c", chDrive);
std::string Directory;
std::string Name;
std::string Extension;
std::string Directory;
std::string Name;
std::string Extension;
GetComponents(nullptr, &Directory, &Name, &Extension);
SetComponents(Drive.c_str(), Directory.c_str(), Name.c_str(), Extension.c_str());
@ -645,9 +663,9 @@ void CPath::SetDrive(char chDrive)
void CPath::SetDirectory(const char * lpszDirectory, bool bEnsureAbsolute /*= false*/)
{
WriteTrace(TracePath, TraceDebug, "Start (lpszDirectory: \"%s\" bEnsureAbsolute: %s)", lpszDirectory ? lpszDirectory : "(null)", bEnsureAbsolute ? "true" : "false");
std::string Directory = lpszDirectory;
std::string Name;
std::string Extension;
std::string Directory = lpszDirectory;
std::string Name;
std::string Extension;
if (bEnsureAbsolute)
{
@ -659,7 +677,7 @@ void CPath::SetDirectory(const char * lpszDirectory, bool bEnsureAbsolute /*= fa
}
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, nullptr, &Name, &Extension);
SetComponents(Drive.c_str(), Directory.c_str(), Name.c_str(), Extension.c_str());
#else
@ -675,9 +693,9 @@ void CPath::SetDirectory(const char * lpszDirectory, bool bEnsureAbsolute /*= fa
void CPath::SetDriveDirectory(const char * lpszDriveDirectory)
{
std::string DriveDirectory = lpszDriveDirectory;
std::string Name;
std::string Extension;
std::string DriveDirectory = lpszDriveDirectory;
std::string Name;
std::string Extension;
if (DriveDirectory.length() > 0)
{
@ -694,11 +712,11 @@ void CPath::SetDriveDirectory(const char * lpszDriveDirectory)
void CPath::SetName(const char * lpszName)
{
std::string Directory;
std::string Extension;
std::string Directory;
std::string Extension;
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, &Directory, nullptr, &Extension);
SetComponents(Drive.c_str(), Directory.c_str(), lpszName, Extension.c_str());
#else
@ -711,16 +729,16 @@ void CPath::SetName(const char * lpszName)
void CPath::SetName(int iName)
{
std::string Directory;
std::string Extension;
char sName[33];
std::string Directory;
std::string Extension;
char sName[33];
memset(sName, 0, sizeof(sName));
_snprintf(sName, sizeof(sName), "%d", iName);
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, &Directory, nullptr, &Extension);
SetComponents(Drive.c_str(), Directory.c_str(), sName, Extension.c_str());
#else
@ -733,11 +751,11 @@ void CPath::SetName(int iName)
void CPath::SetExtension(const char * lpszExtension)
{
std::string Directory;
std::string Name;
std::string Directory;
std::string Name;
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, &Directory, &Name);
SetComponents(Drive.c_str(), Directory.c_str(), Name.c_str(), lpszExtension);
#else
@ -750,8 +768,8 @@ void CPath::SetExtension(const char * lpszExtension)
void CPath::SetExtension(int iExtension)
{
std::string Directory;
std::string Name;
std::string Directory;
std::string Name;
char sExtension[20];
memset(sExtension, 0, sizeof(sExtension));
@ -759,7 +777,7 @@ void CPath::SetExtension(int iExtension)
_snprintf(sExtension, sizeof(sExtension), "%d", iExtension);
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, &Directory, &Name);
SetComponents(Drive.c_str(), Directory.c_str(), Name.c_str(), sExtension);
#else
@ -772,10 +790,10 @@ void CPath::SetExtension(int iExtension)
void CPath::SetNameExtension(const char * lpszNameExtension)
{
std::string Directory;
std::string Directory;
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, &Directory);
SetComponents(Drive.c_str(), Directory.c_str(), lpszNameExtension, nullptr);
#else
@ -788,10 +806,10 @@ void CPath::SetNameExtension(const char * lpszNameExtension)
void CPath::AppendDirectory(const char * lpszSubDirectory)
{
std::string Directory;
std::string SubDirectory = lpszSubDirectory;
std::string Name;
std::string Extension;
std::string Directory;
std::string SubDirectory = lpszSubDirectory;
std::string Name;
std::string Extension;
if (SubDirectory.empty())
{
@ -803,7 +821,7 @@ void CPath::AppendDirectory(const char * lpszSubDirectory)
EnsureTrailingBackslash(SubDirectory);
#ifdef _WIN32
std::string Drive;
std::string Drive;
GetComponents(&Drive, &Directory, &Name, &Extension);
#else
GetComponents(&Directory, &Name, &Extension);
@ -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());
@ -940,21 +958,21 @@ bool CPath::DirectoryExists() const
HANDLE hFindFile = FindFirstFileA((const char *)TestPath, &FindData); // Find anything
bool res = (hFindFile != INVALID_HANDLE_VALUE);
if (hFindFile != nullptr) // Make sure we close the search
if (hFindFile != nullptr) // Make sure we close the search
{
FindClose(hFindFile);
}
#else
std::string PathText;
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;
}
@ -968,7 +986,7 @@ bool CPath::Exists() const
HANDLE hFindFile = FindFirstFileA(m_strPath.c_str(), &FindData);
bool bSuccess = (hFindFile != INVALID_HANDLE_VALUE);
if (hFindFile != nullptr) // Make sure we close the search
if (hFindFile != nullptr) // Make sure we close the search
{
FindClose(hFindFile);
}
@ -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);
}
}
@ -1113,7 +1131,7 @@ bool CPath::CopyTo(const char * lpcszTargetFile, bool bOverwrite)
while (!feof(infile))
{
char buffer[1024];
size_t bytes = fread(buffer, 1, sizeof(buffer), infile);
size_t bytes = fread(buffer, 1, sizeof(buffer), infile);
if (ferror(infile))
{
WriteTrace(TracePath, TraceWarning, "Failed to read from %s", m_strPath.c_str());
@ -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)
@ -1407,48 +1425,48 @@ bool CPath::ChangeDirectory()
void CPath::NormalizePath(CPath BaseDir)
{
#ifdef _WIN32
stdstr Directory = BaseDir.GetDriveDirectory();
stdstr Directory = BaseDir.GetDriveDirectory();
#else
stdstr Directory = BaseDir.GetDirectory();
stdstr Directory = BaseDir.GetDirectory();
#endif
bool Changed = false;
if (IsRelative())
{
EnsureTrailingBackslash(Directory);
Directory += GetDirectory();
Changed = true;
}
strvector Parts = Directory.Tokenize(DIRECTORY_DELIMITER);
strvector NormalizesParts;
for (strvector::const_iterator itr = Parts.begin(); itr != Parts.end(); itr++)
{
if (*itr == ".")
{
Changed = true;
}
else if (*itr == "..")
{
NormalizesParts.pop_back();
Changed = true;
}
else
{
NormalizesParts.push_back(*itr);
}
}
if (Changed)
{
Directory.clear();
for (strvector::const_iterator itr = NormalizesParts.begin(); itr != NormalizesParts.end(); itr++)
{
Directory += *itr + DIRECTORY_DELIMITER;
}
bool Changed = false;
if (IsRelative())
{
EnsureTrailingBackslash(Directory);
Directory += GetDirectory();
Changed = true;
}
strvector Parts = Directory.Tokenize(DIRECTORY_DELIMITER);
strvector NormalizesParts;
for (strvector::const_iterator itr = Parts.begin(); itr != Parts.end(); itr++)
{
if (*itr == ".")
{
Changed = true;
}
else if (*itr == "..")
{
NormalizesParts.pop_back();
Changed = true;
}
else
{
NormalizesParts.push_back(*itr);
}
}
if (Changed)
{
Directory.clear();
for (strvector::const_iterator itr = NormalizesParts.begin(); itr != NormalizesParts.end(); itr++)
{
Directory += *itr + DIRECTORY_DELIMITER;
}
#ifdef _WIN32
SetDriveDirectory(Directory.c_str());
SetDriveDirectory(Directory.c_str());
#else
SetDirectory(Directory.c_str());
SetDirectory(Directory.c_str());
#endif
}
}
}
// Pre: If bCreateIntermediates is TRUE, create all eventually missing parent directories too
@ -1457,9 +1475,9 @@ 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");
std::string PathText;
bool bSuccess;
WriteTrace(TracePath, TraceDebug, "m_strPath = %s bCreateIntermediates = %s", m_strPath.c_str(), bCreateIntermediates ? "true" : "false");
std::string PathText;
bool bSuccess;
if (DirectoryExists())
{
@ -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,30 +1,38 @@
#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
enum
{
FIND_ATTRIBUTE_ALLFILES = 0xFFFF, // Search include all files
FIND_ATTRIBUTE_FILES = 0x0000, // File can be read or written to without restriction
FIND_ATTRIBUTE_SUBDIR = 0x0010, // Subdirectories
};
FIND_ATTRIBUTE_ALLFILES = 0xFFFF, // Search include all files
FIND_ATTRIBUTE_FILES = 0x0000, // File can be read or written to without restriction
FIND_ATTRIBUTE_SUBDIR = 0x0010, // Subdirectories
};
// Attributes
private:
std::string m_strPath;
std::string m_strPath;
#ifdef _WIN32
void * m_hFindFile;
void * m_hFindFile;
static void * m_hInst;
#else
void * m_OpenedDir;
@ -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;
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);
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);
@ -127,7 +147,7 @@ public:
// Directory operations
bool DirectoryCreate(bool bCreateIntermediates = true);
bool ChangeDirectory();
void NormalizePath(CPath BaseDir);
void NormalizePath(CPath BaseDir);
// File operations
bool Delete(bool bEvenIfReadOnly = true) const;
@ -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
};