From: Hamatoma Date: Sat, 28 Feb 2015 20:18:07 +0000 (+0100) Subject: Reformatted with CREPUBLIB rules X-Git-Url: https://gitweb.hamatoma.de/?a=commitdiff_plain;h=3509139c8efded976f50fb925cfb5a55a92aa1a2;p=crepublib Reformatted with CREPUBLIB rules --- diff --git a/base/ReByteBuffer.cpp b/base/ReByteBuffer.cpp index 72618c5..b08ebb6 100644 --- a/base/ReByteBuffer.cpp +++ b/base/ReByteBuffer.cpp @@ -22,13 +22,12 @@ extern int _snprintf (char* s, size_t maxlen, const char* format, ...); * is incremented by at least this count of bytes */ ReByteBuffer::ReByteBuffer(size_t delta) : - m_delta(delta), - // m_primaryBuffer - m_buffer(m_primaryBuffer), - m_length(0), - m_capacity(sizeof m_primaryBuffer - 1), - m_reallocation(0) -{ + m_delta(delta), + // m_primaryBuffer + m_buffer(m_primaryBuffer), + m_length(0), + m_capacity(sizeof m_primaryBuffer - 1), + m_reallocation(0) { m_buffer[0] = '\0'; } /** @brief Constructor. @@ -36,13 +35,12 @@ ReByteBuffer::ReByteBuffer(size_t delta) : * @param source the instance to copy (C string) */ ReByteBuffer::ReByteBuffer(const char* source) : - m_delta(PRIMARY_BUFFER_SIZE), - // m_primaryBuffer - m_buffer(m_primaryBuffer), - m_length(0), - m_capacity(sizeof m_primaryBuffer), - m_reallocation(0) -{ + m_delta(PRIMARY_BUFFER_SIZE), + // m_primaryBuffer + m_buffer(m_primaryBuffer), + m_length(0), + m_capacity(sizeof m_primaryBuffer), + m_reallocation(0) { m_buffer[0] = '\0'; if (source != NULL) append(source); @@ -54,13 +52,12 @@ ReByteBuffer::ReByteBuffer(const char* source) : * @param sourceLength length of source */ ReByteBuffer::ReByteBuffer(const Byte* source, size_t sourceLength) : - m_delta(PRIMARY_BUFFER_SIZE), - // m_primaryBuffer - m_buffer(m_primaryBuffer), - m_length(0), - m_capacity(sizeof m_primaryBuffer - 1), - m_reallocation(0) -{ + m_delta(PRIMARY_BUFFER_SIZE), + // m_primaryBuffer + m_buffer(m_primaryBuffer), + m_length(0), + m_capacity(sizeof m_primaryBuffer - 1), + m_reallocation(0) { m_buffer[0] = '\0'; append(source, sourceLength); } @@ -68,7 +65,7 @@ ReByteBuffer::ReByteBuffer(const Byte* source, size_t sourceLength) : /** @brief Destructor. * */ -ReByteBuffer::~ReByteBuffer(){ +ReByteBuffer::~ReByteBuffer() { if (m_buffer != m_primaryBuffer) delete[] m_buffer; m_buffer = NULL; @@ -80,13 +77,12 @@ ReByteBuffer::~ReByteBuffer(){ * @param source the instance to copy */ ReByteBuffer::ReByteBuffer(const ReByteBuffer& source) : - m_delta(source.delta()), - // m_primaryBuffer - m_buffer(m_primaryBuffer), - m_length(0), - m_capacity(sizeof m_primaryBuffer), - m_reallocation(0) -{ + m_delta(source.delta()), + // m_primaryBuffer + m_buffer(m_primaryBuffer), + m_length(0), + m_capacity(sizeof m_primaryBuffer), + m_reallocation(0) { append(source.buffer(), source.length()); } @@ -96,7 +92,7 @@ ReByteBuffer::ReByteBuffer(const ReByteBuffer& source) : * * @return the instance itself */ -ReByteBuffer& ReByteBuffer::operator =(const ReByteBuffer& source){ +ReByteBuffer& ReByteBuffer::operator =(const ReByteBuffer& source) { m_delta = source.delta(); set(source.buffer(), source.length()); return *this; @@ -116,11 +112,11 @@ ReByteBuffer& ReByteBuffer::operator =(const ReByteBuffer& source){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::append(const Byte* source, size_t length){ +ReByteBuffer& ReByteBuffer::append(const Byte* source, size_t length) { if (length == (size_t) -1) length = strlen(source); ensureSize(m_length + length); - memcpy((void*)(m_buffer + m_length), source, length); + memcpy((void*) (m_buffer + m_length), source, length); m_length += length; m_buffer[m_length] = '\0'; return *this; @@ -138,7 +134,7 @@ ReByteBuffer& ReByteBuffer::append(const Byte* source, size_t length){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::append(const ReByteBuffer& source){ +ReByteBuffer& ReByteBuffer::append(const ReByteBuffer& source) { return append(source.str(), source.length()); } @@ -153,8 +149,8 @@ ReByteBuffer& ReByteBuffer::append(const ReByteBuffer& source){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::append(double value, const char* format){ - char buffer [256]; +ReByteBuffer& ReByteBuffer::append(double value, const char* format) { + char buffer[256]; _snprintf(buffer, sizeof buffer, format, value); append(buffer, -1); @@ -182,18 +178,18 @@ ReByteBuffer& ReByteBuffer::append(double value, const char* format){ * @param padding character used for padding (see minLength) * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::appendFix(const char* data, size_t length, int maxLength, - int minLength, const char* separator, char padding){ +ReByteBuffer& ReByteBuffer::appendFix(const char* data, size_t length, + int maxLength, int minLength, const char* separator, char padding) { if (length == (size_t) -1) length = strlen(data); - if ((int) length < abs(minLength)){ + if ((int) length < abs(minLength)) { ensureSize(m_length + abs(minLength)); if (minLength < 0) - appendChar(padding, - minLength - length); + appendChar(padding, -minLength - length); append(data, length); if (minLength > 0) - appendChar(padding, minLength - length); - } else if ((int) length > maxLength){ + appendChar(padding, minLength - length); + } else if ((int) length > maxLength) { ensureSize(m_length + maxLength); int sepLength = separator == NULL ? 0 : strlen(separator); int lengthPart1 = (maxLength - sepLength + 1) / 2; @@ -233,57 +229,61 @@ ReByteBuffer& ReByteBuffer::appendFix(const char* data, size_t length, int maxLe * @return *this (for chaining) */ ReByteBuffer& ReByteBuffer::appendHexDump(const char* data, size_t length, - int offset, int bytesPerLine, const char* offsetFormat, - bool withAscii, int groupWidth, int gapBehind, const char* separator){ + int offset, int bytesPerLine, const char* offsetFormat, bool withAscii, + int groupWidth, int gapBehind, const char* separator) { if (length == -1) length = strlen(data); if (gapBehind < 0) gapBehind = bytesPerLine / 2; ensureSize(32); int offsetLength = 0; - if (offsetFormat != NULL){ + if (offsetFormat != NULL) { _snprintf(m_buffer, 31, offsetFormat, offset + length); offsetLength = strlen(m_buffer); } - ensureSize((length + bytesPerLine - 1) / bytesPerLine - * (4 + offsetLength + (gapBehind <= 0 ? 0 : bytesPerLine / gapBehind + 1) - + (separator == NULL ? 0 : strlen(separator))+ 1)); - while(length > 0){ + ensureSize( + (length + bytesPerLine - 1) / bytesPerLine + * (4 + offsetLength + + (gapBehind <= 0 ? 0 : bytesPerLine / gapBehind + 1) + + (separator == NULL ? 0 : strlen(separator)) + 1)); + while (length > 0) { if (offsetFormat != NULL) appendInt(offset, offsetFormat); int ix; - for (ix = 0; ix < bytesPerLine; ix++){ + for (ix = 0; ix < bytesPerLine; ix++) { if (ix < (int) length) appendInt((unsigned char) data[ix], "%02x"); else append(" "); if (ix < bytesPerLine - 1 - && (groupWidth == 1 || ix % groupWidth == groupWidth - 1)) + && (groupWidth == 1 || ix % groupWidth == groupWidth - 1)) appendChar(' '); if (ix < bytesPerLine - 1 && gapBehind > 0 - && (gapBehind == 1 || ix % gapBehind == gapBehind - 1)) + && (gapBehind == 1 || ix % gapBehind == gapBehind - 1)) appendChar(' '); } - if (withAscii){ + if (withAscii) { if (separator != NULL) append(separator, -1); char cc; - for (ix = 0; ix < bytesPerLine; ix++){ + for (ix = 0; ix < bytesPerLine; ix++) { if (ix < (int) length) - appendInt( (cc = data[ix]) < ' ' || cc > 127 ? '.' : cc, "%c"); + appendInt((cc = data[ix]) < ' ' || cc > 127 ? '.' : cc, + "%c"); else append(" "); if (ix < bytesPerLine - 1 && gapBehind > 0 - && (gapBehind == 1 || ix % gapBehind == gapBehind - 1)) + && (gapBehind == 1 || ix % gapBehind == gapBehind - 1)) append(" ", 1); } appendChar('\n'); - length = length <= (size_t) bytesPerLine ? 0 : length - bytesPerLine; + length = + length <= (size_t) bytesPerLine ? 0 : length - bytesPerLine; data += bytesPerLine; offset += bytesPerLine; } } - return *this; + return *this; } /** @brief Appends an integer as string at the end of the buffer. @@ -300,8 +300,8 @@ ReByteBuffer& ReByteBuffer::appendHexDump(const char* data, size_t length, * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::appendInt(int number, const char* format){ - char buffer [128]; +ReByteBuffer& ReByteBuffer::appendInt(int number, const char* format) { + char buffer[128]; _snprintf(buffer, sizeof buffer, format, number); append(buffer, -1); @@ -322,8 +322,8 @@ ReByteBuffer& ReByteBuffer::appendInt(int number, const char* format){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::appendInt(unsigned int number, const char* format){ - char buffer [128]; +ReByteBuffer& ReByteBuffer::appendInt(unsigned int number, const char* format) { + char buffer[128]; _snprintf(buffer, sizeof buffer, format, number); append(buffer, -1); @@ -344,8 +344,8 @@ ReByteBuffer& ReByteBuffer::appendInt(unsigned int number, const char* format){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::appendInt(int64_t number, const char* format){ - char buffer [256]; +ReByteBuffer& ReByteBuffer::appendInt(int64_t number, const char* format) { + char buffer[256]; _snprintf(buffer, sizeof buffer, format, number); append(buffer, -1); @@ -366,8 +366,8 @@ ReByteBuffer& ReByteBuffer::appendInt(int64_t number, const char* format){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::appendInt(uint64_t number, const char* format){ - char buffer [256]; +ReByteBuffer& ReByteBuffer::appendInt(uint64_t number, const char* format) { + char buffer[256]; _snprintf(buffer, sizeof buffer, format, number); append(buffer, -1); @@ -383,7 +383,7 @@ ReByteBuffer& ReByteBuffer::appendInt(uint64_t number, const char* format){ * > 12: at least dd:HH:MM:SS.sss
* @return buffer (for chaining) */ -ReByteBuffer& ReByteBuffer::appendMilliSec(int time, int minLength){ +ReByteBuffer& ReByteBuffer::appendMilliSec(int time, int minLength) { int days = time / (24 * 3600 * 1000LL); time %= 24 * 3600 * 1000; int expectedLength = days > 0 ? 12 : 0; @@ -407,7 +407,7 @@ ReByteBuffer& ReByteBuffer::appendMilliSec(int time, int minLength){ appendInt(minutes, stdFormat).append(":"); appendInt(sec, sec > 10 || minimum > 5 ? stdFormat : "%d").append("."); appendInt(msec, "%03d"); - return *this; + return *this; } /** @brief Appends a time (given in milli seconds) as 'dd:HH:MM.mmm'. @@ -419,7 +419,7 @@ ReByteBuffer& ReByteBuffer::appendMilliSec(int time, int minLength){ * > 10: at least dd:HH:MM:SS
* @return buffer (for chaining) */ -ReByteBuffer& ReByteBuffer::appendTime(int time, int minLength){ +ReByteBuffer& ReByteBuffer::appendTime(int time, int minLength) { int days = time / (24 * 3600); time %= 24 * 3600; int expectedLength = days > 0 ? 10 : 0; @@ -441,7 +441,7 @@ ReByteBuffer& ReByteBuffer::appendTime(int time, int minLength){ if (minutes > 0 || minimum > 4) appendInt(minutes, stdFormat).append(":"); appendInt(sec, sec > 10 || minimum > 3 ? stdFormat : "%d"); - return *this; + return *this; } /** Converts a subsequence into an integer. @@ -457,20 +457,22 @@ ReByteBuffer& ReByteBuffer::appendTime(int time, int minLength){ * @param end -1: all found digits will be converted * Otherwise: the maximal number of digits to convert */ -int ReByteBuffer::atoi(size_t start, int end) const{ +int ReByteBuffer::atoi(size_t start, int end) const { int rc = 0; - if (start < m_length){ + if (start < m_length) { if (end < 0) end = m_length; char cc; - if (m_buffer[start] == '0' && tolower(m_buffer[start + 1]) == 'x'){ + if (m_buffer[start] == '0' && tolower(m_buffer[start + 1]) == 'x') { // Hexadecimal number: start += 2; - while (start < (size_t) end && (cc = m_buffer[start++]) >= '0' && isxdigit(cc)) + while (start < (size_t) end && (cc = m_buffer[start++]) >= '0' + && isxdigit(cc)) rc = rc * 16 + (cc <= '9' ? cc - '0' : toupper(cc) - 'A' + 10); } else { // Decimal number: - while (start < (size_t) end && (cc = m_buffer[start++]) >= '0' && cc <= '9') + while (start < (size_t) end && (cc = m_buffer[start++]) >= '0' + && cc <= '9') rc = rc * 10 + cc - '0'; } } @@ -484,12 +486,12 @@ int ReByteBuffer::atoi(size_t start, int end) const{ * @param lengthOfToCount -1: length is strlen(toCount)
* otherwise: length of toCount */ -int ReByteBuffer::count(const char* toCount, size_t lengthToCount){ +int ReByteBuffer::count(const char* toCount, size_t lengthToCount) { int rc = 0; size_t start = 0; - if (lengthToCount == (size_t)-1) + if (lengthToCount == (size_t) -1) lengthToCount = strlen(toCount); - while( (start = indexOf(toCount, lengthToCount, start)) != (size_t) -1){ + while ((start = indexOf(toCount, lengthToCount, start)) != (size_t) -1) { rc++; start += lengthToCount; } @@ -508,12 +510,13 @@ int ReByteBuffer::count(const char* toCount, size_t lengthToCount){ * false: otherwise */ bool ReByteBuffer::endsWith(const Byte* tail, size_t tailLength, - bool ignoreCase) const { + bool ignoreCase) const { bool rc = tail != NULL; - if (rc){ - if (tailLength == (size_t)-1) + if (rc) { + if (tailLength == (size_t) -1) tailLength = strlen(tail); - rc = indexOf(tail, tailLength, m_length - tailLength, m_length, ignoreCase) >= 0; + rc = indexOf(tail, tailLength, m_length - tailLength, m_length, + ignoreCase) >= 0; } return rc; } @@ -527,10 +530,11 @@ bool ReByteBuffer::endsWith(const Byte* tail, size_t tailLength, * * @param size the size will be at least this value */ -void ReByteBuffer::ensureSize(size_t size){ - if (m_capacity < size){ - int delta = m_delta > 0 ? m_delta - : (int) m_capacity < - m_delta / 2 ? (int) 2 * m_capacity : - m_delta; +void ReByteBuffer::ensureSize(size_t size) { + if (m_capacity < size) { + int delta = + m_delta > 0 ? m_delta : + (int) m_capacity < -m_delta / 2 ? (int) 2 * m_capacity : -m_delta; if (int(size - m_capacity) < delta) size = m_capacity + delta; // Think for the ending '\0': @@ -554,10 +558,10 @@ void ReByteBuffer::ensureSize(size_t size){ * @param end the index behind the last filled position. May be behind m_length * @return the instance itself (vor chaining) */ -ReByteBuffer& ReByteBuffer::fill(Byte filler, int start, int end){ +ReByteBuffer& ReByteBuffer::fill(Byte filler, int start, int end) { if (end == -1) end = m_length; - if (start >= 0 && start < end){ + if (start >= 0 && start < end) { if (end > (int) m_length) setLength(end); memset(m_buffer + start, filler, end - start); @@ -574,18 +578,19 @@ ReByteBuffer& ReByteBuffer::fill(Byte filler, int start, int end){ * @return -1: both byte sequences are equal
* otherwise: the index of the first difference */ -int ReByteBuffer::firstDifference(const Byte* source, size_t length, int start, bool ignoreCase){ +int ReByteBuffer::firstDifference(const Byte* source, size_t length, int start, + bool ignoreCase) { int rc = -1; if (start < 0) rc = 0; - else if (start < (int) m_length){ + else if (start < (int) m_length) { if (length == (size_t) -1) length = strlen(source); int count = length > m_length - start ? m_length - start : length; const Byte* ptr = m_buffer + start; - for (int ix = 0; rc < 0 && ix < count; ix++){ - if ((! ignoreCase && *ptr++ != *source++) - || (ignoreCase && (tolower(*ptr++) != tolower(*source++)))) + for (int ix = 0; rc < 0 && ix < count; ix++) { + if ((!ignoreCase && *ptr++ != *source++) + || (ignoreCase && (tolower(*ptr++) != tolower(*source++)))) rc = start + ix; } if (rc < 0 && length > m_length - start) @@ -616,18 +621,19 @@ int ReByteBuffer::firstDifference(const Byte* source, size_t length, int start, * Otherwise: the index of toFind in the internal buffer */ int ReByteBuffer::indexOf(const Byte* toFind, size_t toFindLength, int start, - int end, bool ignoreCase) const{ + int end, bool ignoreCase) const { if (toFindLength == (size_t) -1) toFindLength = strlen(toFind); int rc = -1; if (end < 0 || end > (int) m_length) end = m_length; if (start >= 0 && start <= int(m_length - toFindLength) - && end >= (int) toFindLength && end <= (int) m_length){ - while(rc < 0 && start <= int(end - toFindLength)){ - if (ignoreCase ? _memicmp((void*) toFind, (void*) (m_buffer + start), - toFindLength) == 0 - : _memcmp(toFind, m_buffer + start, toFindLength) == 0) + && end >= (int) toFindLength && end <= (int) m_length) { + while (rc < 0 && start <= int(end - toFindLength)) { + if (ignoreCase ? + _memicmp((void*) toFind, (void*) (m_buffer + start), + toFindLength) == 0 : + _memcmp(toFind, m_buffer + start, toFindLength) == 0) rc = start; else start++; @@ -657,20 +663,21 @@ int ReByteBuffer::indexOf(const Byte* toFind, size_t toFindLength, int start, * Otherwise: the index of toFind in the internal buffer */ int ReByteBuffer::rindexOf(const Byte* toFind, size_t toFindLength, int start, - int end, bool ignoreCase) const{ + int end, bool ignoreCase) const { if (toFindLength == (size_t) -1) toFindLength = strlen(toFind); int rc = -1; if (end < 0 || end > (int) m_length) end = m_length; - if (start >= 0 && start <= int (m_length - toFindLength) - && end >= (int) toFindLength && end <= (int) m_length){ + if (start >= 0 && start <= int(m_length - toFindLength) + && end >= (int) toFindLength && end <= (int) m_length) { int current = end - toFindLength; - while(current >= start){ - if (ignoreCase ? _strnicmp(toFind, m_buffer + current, toFindLength) != 0 - : _memcmp(toFind, m_buffer + current, toFindLength) != 0) + while (current >= start) { + if (ignoreCase ? + _strnicmp(toFind, m_buffer + current, toFindLength) != 0 : + _memcmp(toFind, m_buffer + current, toFindLength) != 0) current--; - else{ + else { rc = current; break; } @@ -696,13 +703,13 @@ int ReByteBuffer::rindexOf(const Byte* toFind, size_t toFindLength, int start, * @param start the first index to inspect */ ReByteBuffer& ReByteBuffer::replaceAll(const Byte* toFind, size_t toFindLength, - const Byte* replacement, size_t replacementLength, int start){ + const Byte* replacement, size_t replacementLength, int start) { if (toFindLength == size_t(-1)) toFindLength = strlen(toFind); if (replacementLength == size_t(-1)) replacementLength = strlen(replacement); - while( (start = indexOf(toFind, toFindLength, start)) != -1){ + while ((start = indexOf(toFind, toFindLength, start)) != -1) { splice(start, toFindLength, replacement, replacementLength); start += replacementLength; } @@ -715,7 +722,7 @@ ReByteBuffer& ReByteBuffer::replaceAll(const Byte* toFind, size_t toFindLength, * 0: delta is set to a default value
* < 0: the current capacity will be doubled until - delta */ -void ReByteBuffer::setDelta(int delta){ +void ReByteBuffer::setDelta(int delta) { m_delta = delta == 0 ? PRIMARY_BUFFER_SIZE : delta; } @@ -735,7 +742,7 @@ void ReByteBuffer::setDelta(int delta){ * * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::setLength(size_t length){ +ReByteBuffer& ReByteBuffer::setLength(size_t length) { ensureSize(length); m_length = length; m_buffer[length] = '\0'; @@ -757,7 +764,7 @@ ReByteBuffer& ReByteBuffer::setLength(size_t length){ * will be filled with this value * @return *this (for chaining) */ -ReByteBuffer& ReByteBuffer::setLengthAndFillOut(size_t length, Byte filler){ +ReByteBuffer& ReByteBuffer::setLengthAndFillOut(size_t length, Byte filler) { ensureSize(length); if (length > m_length) memset(m_buffer + m_length, filler, length - m_length); @@ -786,11 +793,11 @@ ReByteBuffer& ReByteBuffer::setLengthAndFillOut(size_t length, Byte filler){ * @return true: Success. false: ix out of range */ bool ReByteBuffer::splice(size_t ix, size_t replacedLength, - const ReByteBuffer::Byte* source, size_t length){ + const ReByteBuffer::Byte* source, size_t length) { bool rc; if (ix < 0 || ix > m_length) rc = false; - else{ + else { rc = true; if (source == NULL) @@ -806,11 +813,11 @@ bool ReByteBuffer::splice(size_t ix, size_t replacedLength, Byte* tail = start + replacedLength; size_t lengthTail = m_length - ix - replacedLength; - if (length <= replacedLength){ + if (length <= replacedLength) { // The sequence will not be longer: if (length > 0) memcpy(start, source, length); - if (length < replacedLength){ + if (length < replacedLength) { memmove(start + length, tail, lengthTail); } } else { @@ -834,9 +841,10 @@ bool ReByteBuffer::splice(size_t ix, size_t replacedLength, * @return true: the buffer starts with head
* false: otherwise */ -bool ReByteBuffer::startsWith(const Byte* head, size_t headLength, const bool ignoreCase) const{ +bool ReByteBuffer::startsWith(const Byte* head, size_t headLength, + const bool ignoreCase) const { bool rc = head != NULL; - if (rc){ + if (rc) { if (headLength == (size_t) -1) headLength = strlen(head); rc = indexOf(head, headLength, 0, headLength, ignoreCase) == 0; @@ -851,12 +859,13 @@ bool ReByteBuffer::startsWith(const Byte* head, size_t headLength, const bool ig * @param prefix NULL or a prefix of the output * @return buffer.str() (for chaining) */ -const char* ReByteBuffer::status(ReByteBuffer& buffer, const char* prefix) const{ +const char* ReByteBuffer::status(ReByteBuffer& buffer, + const char* prefix) const { if (prefix != NULL) buffer.append(prefix); - buffer.append("capacity:").appendInt(m_capacity) - .append(" length: ").appendInt(m_length) - .append(" realloc: ").appendInt(m_reallocation).append("\n"); + buffer.append("capacity:").appendInt(m_capacity).append(" length: ") + .appendInt(m_length).append(" realloc: ").appendInt(m_reallocation) + .append("\n"); return buffer.str(); } diff --git a/base/ReByteBuffer.hpp b/base/ReByteBuffer.hpp index 63363f6..6914d70 100644 --- a/base/ReByteBuffer.hpp +++ b/base/ReByteBuffer.hpp @@ -11,7 +11,6 @@ #define REBYTEBUFFER_H_ #define PRIMARY_BUFFER_SIZE 513 -#define INLINE /** @brief An efficient dynamic memory buffer. * * Implements a very efficient dynamic byte sequence. @@ -51,7 +50,7 @@ public: * @param aChar character to append * @return *this (for chaining) */ - INLINE ReByteBuffer& appendChar(char aChar){ + inline ReByteBuffer& appendChar(char aChar) { setLength(m_length + 1); m_buffer[m_length - 1] = aChar; return *this; @@ -61,20 +60,20 @@ public: * @param count number of times to append * @return *this (for chaining) */ - INLINE ReByteBuffer& appendChar(char aChar, int count){ - if (count > 0){ + inline ReByteBuffer& appendChar(char aChar, int count) { + if (count > 0) { size_t oldLength = m_length; setLength(m_length + count); memset(m_buffer + oldLength, aChar, count); } return *this; } - ReByteBuffer& appendFix(const char* data, size_t length, int maxLength, - int minLength = 0, const char* separator = "*", char padding = ' '); + ReByteBuffer& appendFix(const char* data, size_t length, int maxLength, + int minLength = 0, const char* separator = "*", char padding = ' '); ReByteBuffer& appendHexDump(const char* data, size_t length = -1, - int offset = 0, int bytePerLine = 16, - const char* offsetFormat = "%04x: ", bool withAscii = true, - int groupWidth = 1, int gapBehind = -1, const char* separator = " | "); + int offset = 0, int bytePerLine = 16, const char* offsetFormat = + "%04x: ", bool withAscii = true, int groupWidth = 1, int gapBehind = + -1, const char* separator = " | "); ReByteBuffer& appendInt(int number, const char* format = "%d"); ReByteBuffer& appendInt(unsigned int number, const char* format = "%d"); ReByteBuffer& appendInt(int64_t number, const char* format = "%lld"); @@ -85,37 +84,37 @@ public: * @param index The index of the wanted byte. * @return 0: Wrong index. Otherwise: The byte from the wanted position. */ - INLINE Byte at(size_t index) const { + inline Byte at(size_t index) const { return index >= m_length ? 0 : m_buffer[index]; } int atoi(size_t start = 0, int end = -1) const; /** @brief Returns the buffer (permitting modifying). * @return The internal used buffer. */ - INLINE Byte* buffer() const{ + inline Byte* buffer() const { return m_buffer; } /**@brief Returns the current size of the internal buffer. * @return The current size of the internal buffer. */ - INLINE size_t capacity() const{ + inline size_t capacity() const { return m_capacity; } int count(const char* toCount, size_t lengthToCount = -1); /**@brief Returns the minimum allocation unit. * @return The minimum of bytes to allocate. */ - INLINE size_t delta() const{ + inline size_t delta() const { return m_delta; } - bool endsWith(const Byte* tail, size_t tailLength = -1, - bool ignoreCase = false) const; + bool endsWith(const Byte* tail, size_t tailLength = -1, bool ignoreCase = + false) const; void ensureSize(size_t size); /** After the call the last character is the given. * @param aChar the character which will be the last * @return *this (for chaining) */ - INLINE ReByteBuffer& ensureLastChar(char aChar){ + inline ReByteBuffer& ensureLastChar(char aChar) { if (lastChar() != aChar) appendChar(aChar); return *this; @@ -126,12 +125,14 @@ public: * @param ignoreCase true: case insensitive comparison * @return true: the buffer's contents are equal */ - INLINE bool equals(const char* data, size_t length, bool ignoreCase = false) const{ + inline + bool equals(const char* data, size_t length, + bool ignoreCase = false) const { if (length == (size_t) -1) length = strlen(data); - bool rc = length == m_length - && (! ignoreCase && _memcmp(data, m_buffer, length) == 0 - || ignoreCase && _strnicmp(data, m_buffer, length) == 0); + bool rc = length == m_length + && (!ignoreCase && _memcmp(data, m_buffer, length) == 0 + || ignoreCase && _strnicmp(data, m_buffer, length) == 0); return rc; } /** @brief Tests whether another instance is equal to this instance. @@ -139,27 +140,31 @@ public: * @param ignoreCase true: case insensitive comparison * @return true: the buffer's contents are equal */ - INLINE bool equals(const ReByteBuffer& buffer, bool ignoreCase = false) const{ - bool rc = buffer.length() == m_length - && (! ignoreCase && _memcmp(buffer.str(), m_buffer, m_length) == 0 - || ignoreCase && _strnicmp(buffer.str(), m_buffer, m_length) == 0); + inline + bool equals(const ReByteBuffer& buffer, bool ignoreCase = false) const { + bool rc = buffer.length() == m_length + && (!ignoreCase && _memcmp(buffer.str(), m_buffer, m_length) == 0 + || ignoreCase + && _strnicmp(buffer.str(), m_buffer, m_length) == 0); return rc; } ReByteBuffer& fill(Byte filler = 0, int start = 0, int end = -1); - int firstDifference(const Byte* source, size_t length, int start = 0, bool ignoreCase = false); + int firstDifference(const Byte* source, size_t length, int start = 0, + bool ignoreCase = false); /** @brief Finds the index of the first occurrence of a given byte. * @param toFind This byte will be searched. * @param start The first index for searching. * @return -1: not found. Otherwise: The index of the first occurrence. */ - INLINE int indexOf(Byte toFind, int start = 0) const { + inline + int indexOf(Byte toFind, int start = 0) const { while ((size_t) start < m_length) if (m_buffer[start++] == toFind) return start - 1; return -1; } - int indexOf(const Byte* toFind, size_t toFindLength, - int start = 0, int end = -1, bool ignoreCase = false) const; + int indexOf(const Byte* toFind, size_t toFindLength, int start = 0, + int end = -1, bool ignoreCase = false) const; /** @brief Inserts a byte sequence. * @param ix The position in the internal buffer for the insertion. * @param source The sequence to insert. @@ -167,28 +172,30 @@ public: * * @return true: Success. false: ix out of range. */ - INLINE bool insert(size_t ix, const Byte* source, size_t length){ + inline + bool insert(size_t ix, const Byte* source, size_t length) { return splice(ix, 0, source, length); } /** Returns the last character. * @return '\0': empty buffer
* otherwise: the last character */ - INLINE char lastChar() const { + inline + char lastChar() const { return m_length == 0 ? '\0' : m_buffer[m_length - 1]; } /**@brief Returns the length of the buffer (the count of used bytes). * @return The count of the allocated bytes in the internal buffer. */ - INLINE size_t length() const{ + inline size_t length() const { return m_length; } /** Sets the length to a lower value. * @param decrement the count to reduce the length * @return The count of the allocated bytes in the internal buffer. */ - INLINE ReByteBuffer& reduceLength(int decrement = 1){ - if (decrement > 0 && m_length > 0){ + inline ReByteBuffer& reduceLength(int decrement = 1) { + if (decrement > 0 && m_length > 0) { if (decrement > (int) m_length) decrement = m_length; setLength(m_length - decrement); @@ -203,16 +210,17 @@ public: * * @return true: Success. false: ix out of range. */ - INLINE bool remove(size_t ix, size_t deletedLength){ + inline + bool remove(size_t ix, size_t deletedLength) { return splice(ix, deletedLength, NULL, 0); } ReByteBuffer& replaceAll(const Byte* toFind, size_t toFindLength, - const Byte* replacement, size_t replacementLength, int start = 0); + const Byte* replacement, size_t replacementLength, int start = 0); /** Removes an unwanted character at the end. * @param aChar character to remove * @return *this (for chaining) */ - INLINE ReByteBuffer& removeLastChar(char aChar){ + inline ReByteBuffer& removeLastChar(char aChar) { if (m_length > 0 && m_buffer[m_length - 1] == aChar) setLength(m_length - 1); return *this; @@ -222,56 +230,59 @@ public: * @param start The first index for searching. If < 0: relative to the end. * @return -1: not found. Otherwise: The index of the last occurrence. */ - INLINE int rindexOf(Byte toFind, int start = -1) const { + inline + int rindexOf(Byte toFind, int start = -1) const { if (start < 0) - start = m_length + start; + start = m_length + start; while (start >= 0) if (m_buffer[start--] == toFind) return start + 1; return -1; } - int rindexOf(const Byte* toFind, size_t toFindLength, - int start = 0, int end = -1, bool ignoreCase = false) const; + int rindexOf(const Byte* toFind, size_t toFindLength, int start = 0, + int end = -1, bool ignoreCase = false) const; /** @brief Sets the content of the buffer by copying a byte sequence. * @param source The byte sequence to copy. * @param length The length of source. * @return *this (for chaining). */ - INLINE ReByteBuffer& set(const Byte* source, size_t length){ + inline ReByteBuffer& set(const Byte* source, size_t length) { return setLength(0).append(source, length); } /** @brief Sets the content of the buffer by copying a byte sequence. * @param source the source to copy. * @return *this (for chaining). */ - INLINE ReByteBuffer& set(const ReByteBuffer& source){ + inline ReByteBuffer& set(const ReByteBuffer& source) { return setLength(0).append(source); } void setDelta(int delta); ReByteBuffer& setLength(size_t length); ReByteBuffer& setLengthAndFillOut(size_t length, Byte filler = 0); - bool splice(size_t ix, size_t replacedLength, const Byte* source, size_t length); + bool splice(size_t ix, size_t replacedLength, const Byte* source, + size_t length); bool startsWith(const Byte* head, size_t headLength = -1, - const bool ignoreCase = false) const; + const bool ignoreCase = false) const; const char* status(ReByteBuffer& buffer, const char* prefix = NULL) const; /** @brief Returns the buffer content as C string. * This is exactly the same result as from getBuffer(). * @return The internal used buffer. */ - INLINE const char* str() const{ + inline + const char* str() const { return (const char*) m_buffer; } protected: - // The minimum difference between old and new size after a new allocation. - int m_delta; - //@ If the needed space is small enough this buffer will be used. - char m_primaryBuffer[PRIMARY_BUFFER_SIZE]; - //@ The internal buffer. Points to m_primaryBuffer if the space is small enough. - char* m_buffer; - //@ The used bytes in m_buffer. - size_t m_length; - //@ The size of m_buffer. - size_t m_capacity; + // The minimum difference between old and new size after a new allocation. + int m_delta; + //@ If the needed space is small enough this buffer will be used. + char m_primaryBuffer[PRIMARY_BUFFER_SIZE]; + //@ The internal buffer. Points to m_primaryBuffer if the space is small enough. + char* m_buffer; + //@ The used bytes in m_buffer. + size_t m_length; + //@ The size of m_buffer. + size_t m_capacity; //@ number of reallocation in ensureSize() int m_reallocation; }; diff --git a/base/ReCString.cpp b/base/ReCString.cpp index a81d72a..28e7b01 100644 --- a/base/ReCString.cpp +++ b/base/ReCString.cpp @@ -19,26 +19,25 @@ * @param newString The string which will be inserted. */ void replaceSubstring(char* start, size_t bufferSize, size_t lengthReplaced, - const char* newString) -{ + const char* newString) { size_t lengthNew = strlen(newString); char* tail = start + lengthReplaced; size_t lengthTail = strlen(tail) + 1; - if (lengthNew <= lengthReplaced){ + if (lengthNew <= lengthReplaced) { // The string will not be longer: memcpy(start, newString, lengthNew); - if (lengthNew < lengthReplaced){ + if (lengthNew < lengthReplaced) { memmove(start + lengthNew, tail, lengthTail); } } else { // The string will be longer: if (lengthTail + lengthNew - lengthReplaced > bufferSize) - globalLogger()->sayF(LOG_ERROR|GRAN_USER|CAT_LIB, LC_CSTRING_REPLACE_1, - i18n("+++ The name size exceeds: $1 / $2\n")) - .arg(int(lengthTail + lengthNew - lengthReplaced)) - .arg((int) bufferSize) - .end(); + globalLogger()->sayF(LOG_ERROR | GRAN_USER | CAT_LIB, + LC_CSTRING_REPLACE_1, + i18n("+++ The name size exceeds: $1 / $2\n")).arg( + int(lengthTail + lengthNew - lengthReplaced)).arg( + (int) bufferSize).end(); else { memmove(start + lengthNew, tail, lengthTail); memcpy(start, newString, lengthNew); @@ -57,20 +56,20 @@ void replaceSubstring(char* start, size_t bufferSize, size_t lengthReplaced, */ int _memicmp(const void* region1, const void* region2, int size) { - unsigned char* ptr1 = (unsigned char*) region1; - unsigned char* ptr2 = (unsigned char*) region2; - int rc = 0; - for (int ix = 0; ix < size; ix++){ - unsigned char cc1 = *ptr1++; - unsigned char cc2 = *ptr2++; - int diff = tolower(cc1) - tolower(cc2); - if (diff != 0) - { - rc = diff; - break; - } - } - return rc; + unsigned char* ptr1 = (unsigned char*) region1; + unsigned char* ptr2 = (unsigned char*) region2; + int rc = 0; + for (int ix = 0; ix < size; ix++) { + unsigned char cc1 = *ptr1++; + unsigned char cc2 = *ptr2++; + int diff = tolower(cc1) - tolower(cc2); + if (diff != 0) + { + rc = diff; + break; + } + } + return rc; } #endif diff --git a/base/ReCString.hpp b/base/ReCString.hpp index 3088ad2..65ae90d 100644 --- a/base/ReCString.hpp +++ b/base/ReCString.hpp @@ -11,7 +11,7 @@ #define RESTRING_H_ void replaceSubstring(char* start, size_t bufferSize, size_t lengthReplaced, - const char* newString); + const char* newString); #if defined __linux__ int _memicmp(const void* region1, const void* region2, int size); #endif diff --git a/base/ReConfigFile.cpp b/base/ReConfigFile.cpp index a7969a2..38fdb23 100644 --- a/base/ReConfigFile.cpp +++ b/base/ReConfigFile.cpp @@ -22,12 +22,10 @@ const char* ReConfigFile::m_falseValues = i18nm(";false;f;0;n;nein;no;"); * * @param filename The name of the configuration file. */ -ReConfigFile::ReConfigFile(const char* filename) - : - ReHashList(), - m_filename(), - m_valid(false) -{ +ReConfigFile::ReConfigFile(const char* filename) : + ReHashList(), + m_filename(), + m_valid(false) { readFile(filename); } @@ -45,7 +43,7 @@ ReConfigFile::~ReConfigFile() { * * @param filename The name of the configuration file. */ -void ReConfigFile::readFile(const char* filename){ +void ReConfigFile::readFile(const char* filename) { m_valid = false; m_filename.set(filename, -1); clear(); @@ -54,21 +52,22 @@ void ReConfigFile::readFile(const char* filename){ char* equal; ReByteBuffer buffer; - if (fp != NULL){ + if (fp != NULL) { int lineNo = 0; - while (fgets(line, sizeof line, fp) != NULL){ + while (fgets(line, sizeof line, fp) != NULL) { lineNo++; - if (isalnum(line[0]) && (equal = strchr(line, '=')) != NULL){ + if (isalnum(line[0]) && (equal = strchr(line, '=')) != NULL) { size_t ix = strlen(line) - 1; // Remove all newlines: - while (ix > 0 && isspace(line[ix])){ + while (ix > 0 && isspace(line[ix])) { line[ix] = '\0'; ix--; } *equal = '\0'; if (get(line, -1, buffer)) - globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_CONFIGFILE_DOUBLE, - "$1-$2: Key is defined again: $3").arg(filename).arg(lineNo).arg(line).end(); + globalLogger()->sayF(LOG_ERROR | CAT_LIB, + LC_CONFIGFILE_DOUBLE, "$1-$2: Key is defined again: $3") + .arg(filename).arg(lineNo).arg(line).end(); else put(line, -1, equal + 1, -1); } @@ -83,13 +82,14 @@ void ReConfigFile::readFile(const char* filename){ * * @return The wanted integer or the default value. */ -int ReConfigFile::getInteger(const char* key, int defaultVal){ +int ReConfigFile::getInteger(const char* key, int defaultVal) { ReByteBuffer value; getString(key, value, NULL); int rc = defaultVal; - if (! isdigit(value.at(0))) + if (!isdigit(value.at(0))) globalLogger()->sayF(LOG_WARNING | CAT_LIB, LC_CONFIGFILE_NO_INT, - "$1: Not an integer: $2 [$3]").arg(m_filename.str()).arg(value.str()).arg(key).end(); + "$1: Not an integer: $2 [$3]").arg(m_filename.str()).arg( + value.str()).arg(key).end(); else rc = value.atoi(); return rc; @@ -100,8 +100,9 @@ int ReConfigFile::getInteger(const char* key, int defaultVal){ * @param buffer Out: The buffer for the result string. * @param defaultVal If the key could not found this value will be returned. May be NULL. */ -void ReConfigFile::getString(const char* key, ReByteBuffer& buffer, const char* defaultVal){ - if (! get(key, -1, buffer)){ +void ReConfigFile::getString(const char* key, ReByteBuffer& buffer, + const char* defaultVal) { + if (!get(key, -1, buffer)) { if (defaultVal == NULL) buffer.setLength(0); else @@ -115,7 +116,7 @@ void ReConfigFile::getString(const char* key, ReByteBuffer& buffer, const char* * * @return The wanted boolean or the default value. */ -bool ReConfigFile::getBool(const char* key, bool defaultVal){ +bool ReConfigFile::getBool(const char* key, bool defaultVal) { ReByteBuffer value; getString(key, value, NULL); bool rc = defaultVal; @@ -125,8 +126,8 @@ bool ReConfigFile::getBool(const char* key, bool defaultVal){ rc = true; else globalLogger()->sayF(LOG_WARNING | CAT_LIB, LC_CONFIGFILE_NO_BOOL, - "$1: Not an boolean: $2 [$3] Allowed: $4$5").arg(m_filename.str()) - .arg(value.str()).arg(key).arg(i18n(m_falseValues)) - .arg(i18n(m_trueValues)).end(); + "$1: Not an boolean: $2 [$3] Allowed: $4$5").arg(m_filename.str()) + .arg(value.str()).arg(key).arg(i18n(m_falseValues)).arg( + i18n(m_trueValues)).end(); return rc; } diff --git a/base/ReConfigFile.hpp b/base/ReConfigFile.hpp index 507ac17..053aacf 100644 --- a/base/ReConfigFile.hpp +++ b/base/ReConfigFile.hpp @@ -10,7 +10,7 @@ #ifndef RECONFIGFILE_H_ #define RECONFIGFILE_H_ -class ReConfigFile : protected ReHashList { +class ReConfigFile: protected ReHashList { public: static const char* m_trueValues; static const char* m_falseValues; @@ -25,7 +25,8 @@ private: public: void readFile(const char* filename); int getInteger(const char* key, int defaultVal = 0); - void getString(const char* key, ReByteBuffer& buffer, const char* defaultVal = NULL); + void getString(const char* key, ReByteBuffer& buffer, + const char* defaultVal = NULL); bool getBool(const char* key, bool defaultVal = false); /** @brief Returns whether the instance is in a valid state. * @return true: The configuration is valid. false: Otherwise. @@ -34,8 +35,8 @@ public: return m_valid; } protected: - ReByteBuffer m_filename; - bool m_valid; + ReByteBuffer m_filename; + bool m_valid; }; #endif /* RECONFIGFILE_H_ */ diff --git a/base/ReDirectory.cpp b/base/ReDirectory.cpp index d9daca8..5c7afde 100644 --- a/base/ReDirectory.cpp +++ b/base/ReDirectory.cpp @@ -12,42 +12,40 @@ /** @brief Constructor. */ ReDirectory::ReDirectory() : - m_valid(false), - m_path(), - m_pattern(), + m_path(), + m_pattern(), #if defined __linux__ - m_dir(NULL), - m_entry(NULL), - // m_regExpr - m_regExprFlags(0), - m_regExprIsInitialized(false), - m_isRegExpr(false) + m_dir(NULL), + m_entry(NULL), +// m_regExpr + m_regExprFlags(0), + m_regExprIsInitialized(false), + m_isRegExpr(false), #elif defined __WIN32__ - m_handle(INVALID_HANDLE_VALUE) - //m_data() + m_handle(INVALID_HANDLE_VALUE), +//m_data() #endif -{ + m_valid(false) { } /** @brief Constructor. * * @param path The path of the directory. */ ReDirectory::ReDirectory(const char* path) : - m_valid(false), - m_path(), - m_pattern(), + m_path(), + m_pattern(), #if defined __linux__ - m_dir(NULL), - m_entry(NULL), - // m_regExpr - m_regExprFlags(0), - m_regExprIsInitialized(false), - m_isRegExpr(false) + m_dir(NULL), + m_entry(NULL), +// m_regExpr + m_regExprFlags(0), + m_regExprIsInitialized(false), + m_isRegExpr(false), #elif defined __WIN32__ - m_handle(0) - //m_data() + m_handle(0), +//m_data(), #endif -{ + m_valid(false) { #if defined __linux__ memset(&m_regExpr, 0, sizeof m_regExpr); #endif @@ -55,22 +53,22 @@ ReDirectory::ReDirectory(const char* path) : } /** @brief Destructor. */ -ReDirectory::~ReDirectory(){ +ReDirectory::~ReDirectory() { close(); } /** @brief Frees the resources. -*/ -void ReDirectory::close(){ + */ +void ReDirectory::close() { #if defined __linux__ - if (m_dir != NULL){ + if (m_dir != NULL) { closedir(m_dir); m_dir = NULL; m_valid = false; } if (m_regExprIsInitialized) - regfree(&m_regExpr); + regfree(&m_regExpr); #elif defined __WIN32__ - if (m_handle != INVALID_HANDLE_VALUE){ + if (m_handle != INVALID_HANDLE_VALUE) { FindClose(m_handle); m_handle = INVALID_HANDLE_VALUE; } @@ -82,13 +80,13 @@ void ReDirectory::close(){ * @return NULL: No current file exists. Otherwise: The name of the current file. * */ -const char* ReDirectory::currentFile(){ +const char* ReDirectory::currentFile() { #if defined __linux__ const char* rc = m_entry == NULL ? NULL : m_entry->d_name; #elif defined __WIN32__ - const char* rc = m_data.cFileName; + const char* rc = m_data.cFileName; #endif - return rc; + return rc; } /** @@ -98,29 +96,30 @@ const char* ReDirectory::currentFile(){ * @param deleteBaseToo true: the directory itself will be deleted * false: only the files and subdirs in the dir will be deleted */ -void ReDirectory::deleteTree(const char* base, bool deleteBaseToo){ - if (true){ - ReDirectory dir(base); - if (dir.findFirst("*", false)){ - ReByteBuffer full; - do { - struct stat info; - const char* node = dir.currentFile(); - if (! (node[0] == '.' && (node[1] == '\0' || node[1] == '.' && node[2] == '\0')) - && stat(dir.fullpath(full).str(), &info) == 0){ - if (S_ISDIR(info.st_mode)) - deleteTree(full.str(), true); - else - _unlink(full.str()); - } - } while(dir.findNext()); - } - dir.close(); - if (deleteBaseToo){ - _rmdir(base); +void ReDirectory::deleteTree(const char* base, bool deleteBaseToo) { + if (true) { + ReDirectory dir(base); + if (dir.findFirst("*", false)) { + ReByteBuffer full; + do { + struct stat info; + const char* node = dir.currentFile(); + if (!(node[0] == '.' + && (node[1] == '\0' || node[1] == '.' && node[2] == '\0')) + && stat(dir.fullpath(full).str(), &info) == 0) { + if (S_ISDIR(info.st_mode)) + deleteTree(full.str(), true); + else + _unlink(full.str()); + } + } while (dir.findNext()); + } + dir.close(); + if (deleteBaseToo) { + _rmdir(base); + } } } -} /** @brief Returns the name of the directory. * @@ -137,19 +136,19 @@ const char* ReDirectory::getDir(void) const { * * @return true: A file has been found. false: The directory contains no file with the given pattern. */ -bool ReDirectory::findFirst(const char* pattern, bool isRegExpr){ +bool ReDirectory::findFirst(const char* pattern, bool isRegExpr) { bool rc = false; - if (m_valid){ + if (m_valid) { m_pattern.set(pattern, -1); #if defined __linux__ m_isRegExpr = isRegExpr; - if (isRegExpr){ + if (isRegExpr) { if (m_regExprIsInitialized) - regfree(&m_regExpr); + regfree(&m_regExpr); int rc2 = regcomp(&m_regExpr, pattern, m_regExprFlags); m_regExprIsInitialized = true; - if (rc2 != 0){ + if (rc2 != 0) { rc = false; } else { rewinddir(m_dir); @@ -162,10 +161,10 @@ bool ReDirectory::findFirst(const char* pattern, bool isRegExpr){ rc = findNext(); } #elif defined __WIN32__ - ReByteBuffer full(m_path); - full.append(OS_SEPARATOR, -1).append(pattern, -1); - m_handle = FindFirstFileA(full.str(), &m_data); - rc = m_handle != INVALID_HANDLE_VALUE; + ReByteBuffer full(m_path); + full.append(OS_SEPARATOR, -1).append(pattern, -1); + m_handle = FindFirstFileA(full.str(), &m_data); + rc = m_handle != INVALID_HANDLE_VALUE; #endif } return rc; @@ -175,24 +174,24 @@ bool ReDirectory::findFirst(const char* pattern, bool isRegExpr){ * @return true: a file has been found
* false: the directory contains no more file with the given pattern */ -bool ReDirectory::findNext(){ +bool ReDirectory::findNext() { bool rc = false; - if (m_valid){ + if (m_valid) { #if defined __linux__ - while (! rc && (m_entry = readdir(m_dir)) != NULL){ - if (m_isRegExpr){ + while (! rc && (m_entry = readdir(m_dir)) != NULL) { + if (m_isRegExpr) { regmatch_t match[10]; int rc2 = regexec (&m_regExpr, m_entry->d_name, sizeof match / sizeof match[0], match, 0); if (rc2 == 0) - rc = true; + rc = true; } else { if (fnmatch(m_pattern.str(), m_entry->d_name, 0) == 0) - rc = true; + rc = true; } } #elif defined __WIN32__ - if (m_handle != INVALID_HANDLE_VALUE) - rc = FindNextFileA(m_handle, &m_data) != 0; + if (m_handle != INVALID_HANDLE_VALUE) + rc = FindNextFileA(m_handle, &m_data) != 0; #endif } return rc; @@ -205,7 +204,7 @@ bool ReDirectory::findNext(){ * * @param false: No file found. true: A file was found. */ -bool ReDirectory::findYoungest(ReByteBuffer& filename){ +bool ReDirectory::findYoungest(ReByteBuffer& filename) { bool rc = false; filename.setLength(0); ReByteBuffer fullname; @@ -213,38 +212,38 @@ bool ReDirectory::findYoungest(ReByteBuffer& filename){ #if defined __linux__ if (m_entry != NULL) { - fullname.append(m_path); - size_t length = fullname.length(); - struct stat info; + fullname.append(m_path); + size_t length = fullname.length(); + struct stat info; timespec youngest; youngest.tv_sec = youngest.tv_nsec = 0; - do{ + do { fullname.setLength(length); fullname.append(m_entry->d_name, -1); if (stat(fullname.str(), &info) == 0 - && (info.st_mtim.tv_sec > youngest.tv_sec - || (info.st_mtim.tv_sec == youngest.tv_sec - && info.st_mtim.tv_nsec > youngest.tv_nsec))){ + && (info.st_mtim.tv_sec > youngest.tv_sec + || (info.st_mtim.tv_sec == youngest.tv_sec + && info.st_mtim.tv_nsec > youngest.tv_nsec))) { youngest = info.st_mtim; filename.set(m_entry->d_name, -1); rc = true; } - } while(findNext()); + }while(findNext()); } #elif defined __WIN32__ - FILETIME youngest; - memset(&youngest, 0, sizeof youngest); - do{ - if (m_data.ftLastWriteTime.dwHighDateTime > youngest.dwHighDateTime - || m_data.ftLastWriteTime.dwHighDateTime == youngest.dwHighDateTime - && m_data.ftLastWriteTime.dwLowDateTime > youngest.dwLowDateTime){ - youngest = m_data.ftLastWriteTime; - filename.set(m_data.cFileName, -1); - rc = true; - } + FILETIME youngest; + memset(&youngest, 0, sizeof youngest); + do { + if (m_data.ftLastWriteTime.dwHighDateTime > youngest.dwHighDateTime + || m_data.ftLastWriteTime.dwHighDateTime == youngest.dwHighDateTime + && m_data.ftLastWriteTime.dwLowDateTime > youngest.dwLowDateTime) { + youngest = m_data.ftLastWriteTime; + filename.set(m_data.cFileName, -1); + rc = true; + } - } while(findNext()); + }while(findNext()); #endif return rc; } @@ -260,19 +259,19 @@ bool ReDirectory::findYoungest(ReByteBuffer& filename){ * * @return path (for chaining). */ -ReByteBuffer& ReDirectory::fullpath(ReByteBuffer& path, const char* name){ +ReByteBuffer& ReDirectory::fullpath(ReByteBuffer& path, const char* name) { path.setLength(0); - if (name != NULL){ - path.set(m_path.str(), m_path.length()); + if (name != NULL) { + path.set(m_path.str(), m_path.length()); path.append(name, -1); - } else if (m_valid){ + } else if (m_valid) { #if defined __linux__ - if (m_entry != NULL){ - path.append(m_path); - path.append(m_entry->d_name, -1); - } + if (m_entry != NULL) { + path.append(m_path); + path.append(m_entry->d_name, -1); + } #elif defined __WIN32__ - path.set(m_path.str(), m_path.length()); + path.set(m_path.str(), m_path.length()); path.append(m_data.cFileName, -1); #endif } @@ -283,7 +282,7 @@ ReByteBuffer& ReDirectory::fullpath(ReByteBuffer& path, const char* name){ * * @return true: The instance is OK. false: Some error has occurred. */ -bool ReDirectory::isValid(){ +bool ReDirectory::isValid() { return m_valid; } @@ -291,10 +290,10 @@ bool ReDirectory::isValid(){ * * @param path The name of the directory. */ -void ReDirectory::setDir(const char* path){ +void ReDirectory::setDir(const char* path) { m_path.set(path, -1); #if defined __linux__ - if (m_dir != NULL){ + if (m_dir != NULL) { closedir(m_dir); m_dir = NULL; } @@ -302,10 +301,10 @@ void ReDirectory::setDir(const char* path){ m_dir = opendir(path); m_valid = m_dir != NULL; #elif defined __WIN32__ - struct stat info; - ReByteBuffer thePath(m_path); - thePath.removeLastChar(OS_SEPARATOR_CHAR); - m_valid = stat(thePath.str(), &info) == 0 && S_ISDIR(info.st_mode); + struct stat info; + ReByteBuffer thePath(m_path); + thePath.removeLastChar(OS_SEPARATOR_CHAR); + m_valid = stat(thePath.str(), &info) == 0 && S_ISDIR(info.st_mode); #endif if (m_path.lastChar() != OS_SEPARATOR_CHAR) m_path.appendChar(OS_SEPARATOR_CHAR); @@ -315,7 +314,7 @@ void ReDirectory::setDir(const char* path){ * * @param flags Usefull flags are: REG_ICASE: ignore case. */ -void ReDirectory::setRegExprFlags(int flags){ +void ReDirectory::setRegExprFlags(int flags) { #if defined __linux__ m_regExprFlags = flags; #endif diff --git a/base/ReDirectory.hpp b/base/ReDirectory.hpp index 315dbda..36428a4 100644 --- a/base/ReDirectory.hpp +++ b/base/ReDirectory.hpp @@ -11,7 +11,7 @@ #define REFILEFINDER_H_ /** ReDirectory searches files using pattern matching and/or file date. */ -class ReDirectory{ +class ReDirectory { public: ReDirectory(); ReDirectory(const char* path); @@ -30,22 +30,22 @@ public: public: static void deleteTree(const char* base, bool deleteBaseToo = false); private: - //@ true: The directory is ok. false: The directory is undefined. - bool m_valid; - //@ The name of the current directory. Always ends with slash! + //@ The name of the current directory. Always ends with slash! ReByteBuffer m_path; ReByteBuffer m_pattern; #if defined __linux__ - DIR* m_dir; + DIR* m_dir; struct dirent* m_entry; regex_t m_regExpr; int m_regExprFlags; bool m_regExprIsInitialized; - // Flags for the regular expressions: REG_ICASE: ignore Case. + // Flags for the regular expressions: REG_ICASE: ignore Case. bool m_isRegExpr; #elif defined __WIN32__ - HANDLE m_handle; - WIN32_FIND_DATAA m_data; + HANDLE m_handle; + WIN32_FIND_DATAA m_data; #endif + //@ true: The directory is ok. false: The directory is undefined. + bool m_valid; }; #endif /* REFILEFINDER_H_ */ diff --git a/base/ReException.cpp b/base/ReException.cpp index e2a2bfb..cfe1f93 100644 --- a/base/ReException.cpp +++ b/base/ReException.cpp @@ -14,20 +14,16 @@ * This constructor is for derived classes only. * The constructor of the derived class must fill the m_message. */ -ReException::ReException() - : - m_message(NULL) -{ +ReException::ReException() : + m_message(NULL) { } /** @brief Constructor. * * @param message The error message. */ -ReException::ReException(const char* message) - : - m_message(_strdup(message)) -{ +ReException::ReException(const char* message) : + m_message(_strdup(message)) { } /** @brief Constructor. * @@ -35,27 +31,23 @@ ReException::ReException(const char* message) * @param file The name of the file where the exception is thrown. * @param lineNo The line no name of the file where the exception is thrown. */ -ReException::ReException(const char* message, const char* file, int lineNo) - : - m_message(NULL) -{ +ReException::ReException(const char* message, const char* file, int lineNo) : + m_message(NULL) { char buffer[512]; _snprintf(buffer, sizeof buffer, "%s [%.100s-%d]", message, file, lineNo); m_message = _strdup(buffer); } /** @brief Destructor. */ -ReException::~ReException(){ +ReException::~ReException() { if (m_message != NULL) - free((void*)m_message); + free((void*) m_message); } -ReException::ReException(const ReException& source) - : - m_message(_strdup(source.getMessage())) -{ +ReException::ReException(const ReException& source) : + m_message(_strdup(source.getMessage())) { } -ReException& ReException::operator =(const ReException& source){ +ReException& ReException::operator =(const ReException& source) { if (m_message != NULL) free((void*) m_message); m_message = _strdup(source.getMessage()); @@ -68,12 +60,11 @@ ReException& ReException::operator =(const ReException& source){ * @param format The format string with the error. */ -ReFormatException::ReFormatException(const char* message, const char* format) - : - ReException() -{ +ReFormatException::ReFormatException(const char* message, const char* format) : + ReException() { char buffer[512]; - _snprintf(buffer, sizeof buffer, "%s%s", message, format == NULL ? "" : format); + _snprintf(buffer, sizeof buffer, "%s%s", message, + format == NULL ? "" : format); m_message = _strdup(buffer); } @@ -85,13 +76,11 @@ ReFormatException::ReFormatException(const char* message, const char* format) * @param lineNo The line no name of the file where the exception is thrown. */ ReFormatException::ReFormatException(const char* message, const char* format, - const char* file, int lineNo) - : - ReException() -{ + const char* file, int lineNo) : + ReException() { char buffer[512]; - _snprintf(buffer, sizeof buffer, "%s%s [%.100s-%d]", - message, format == NULL ? "" : format, file, lineNo); + _snprintf(buffer, sizeof buffer, "%s%s [%.100s-%d]", message, + format == NULL ? "" : format, file, lineNo); m_message = _strdup(buffer); } @@ -101,11 +90,12 @@ ReFormatException::ReFormatException(const char* message, const char* format, * @param index The index which violates the array bounds. * @param bound The bound of the array: upper or lower. */ -ReBoundsException::ReBoundsException(const char* name, int index, int bound) -{ +ReBoundsException::ReBoundsException(const char* name, int index, int bound) { char buffer[256]; - const char* format = index < bound - ? i18n("%s: index underflow: %d / %d") : i18n("%s: index overflow: %d / %d"); + const char* format = + index < bound ? + i18n("%s: index underflow: %d / %d") : + i18n("%s: index overflow: %d / %d"); _snprintf(buffer, sizeof buffer, format, name, index, bound); m_message = _strdup(buffer); } @@ -117,13 +107,14 @@ ReBoundsException::ReBoundsException(const char* name, int index, int bound) * @param file The name of the file where the exception is thrown. * @param lineNo The line no name of the file where the exception is thrown. */ -ReBoundsException::ReBoundsException(const char* name, int index, int bound, const char* file, int line) - : - ReException() -{ +ReBoundsException::ReBoundsException(const char* name, int index, int bound, + const char* file, int line) : + ReException() { char buffer[256]; - const char* format = index < bound - ? i18n("%s: index underflow: %d / %d [%s-%d]") : i18n("%s: index overflow: %d / %d [%s-%d]"); + const char* format = + index < bound ? + i18n("%s: index underflow: %d / %d [%s-%d]") : + i18n("%s: index overflow: %d / %d [%s-%d]"); _snprintf(buffer, sizeof buffer, format, name, index, bound, file, line); m_message = _strdup(buffer); } diff --git a/base/ReException.hpp b/base/ReException.hpp index ef4a12a..77999e5 100644 --- a/base/ReException.hpp +++ b/base/ReException.hpp @@ -26,7 +26,7 @@ public: /** @brief Sets the message. * @param message The new message. */ - inline void setMessage(const char* message){ + inline void setMessage(const char* message) { if (m_message != NULL) free((void *) m_message); m_message = _strdup(message); @@ -34,7 +34,7 @@ public: /** @brief Returns the message. * @returns The description of the exception. */ - inline const char* getMessage() const{ + inline const char* getMessage() const { return m_message; } protected: @@ -42,17 +42,19 @@ protected: }; /** This exception is used on format errors. */ -class ReFormatException : public ReException{ +class ReFormatException: public ReException { public: ReFormatException(const char* message, const char* format); - ReFormatException(const char* message, const char* format, const char* file, int line); + ReFormatException(const char* message, const char* format, const char* file, + int line); }; /** This exception is called when an index underflow or overflow is done. */ -class ReBoundsException : public ReException{ +class ReBoundsException: public ReException { public: ReBoundsException(const char* name, int index, int bound); - ReBoundsException(const char* name, int index, int bound, const char* file, int line); + ReBoundsException(const char* name, int index, int bound, const char* file, + int line); }; #endif /* REEXCEPTION_H_ */ diff --git a/base/ReHashList.cpp b/base/ReHashList.cpp index a217277..5d8d18c 100644 --- a/base/ReHashList.cpp +++ b/base/ReHashList.cpp @@ -10,40 +10,38 @@ #include "base/rebase.hpp" enum RELOC_HASHLIST { - LC_NEXT_1 = LC_HASHLIST + 1, // 50301 + LC_NEXT_1 = LC_HASHLIST + 1, // 50301 }; /** * Constructor. */ ReArrayPosition::ReArrayPosition() : - m_position(-1), - m_forward(true) -{ + m_position(-1), + m_forward(true) { } /** * Sets the cursor behind the last position. * * Calling ReHashList::prior() returns the last element. */ -void ReArrayPosition::behindLast(){ +void ReArrayPosition::behindLast() { m_position = (ReSeqArray::Index) -2; } /** * Sets the cursor behind the last position. * Calling ReHashList::next() returns the first element. */ -void ReArrayPosition::priorFirst(){ +void ReArrayPosition::priorFirst() { m_position = (ReSeqArray::Index) -1; } /** Constructor. */ ReHashList::ReHashList(bool ignoreCase, int keyTagSize, int contentLengthSize, - int keyLengthSize) : - m_keys(), - m_values() -{ + int keyLengthSize) : + m_keys(), + m_values() { m_keys.setIgnoreCase(ignoreCase); m_keys.setSorted(true); m_keys.setSizes(keyTagSize, keyLengthSize); @@ -56,7 +54,7 @@ ReHashList::~ReHashList() { /** @brief Deletes all entries in the list. */ -void ReHashList::clear(){ +void ReHashList::clear() { m_keys.clear(); m_values.clear(); } @@ -67,13 +65,14 @@ void ReHashList::clear(){ * @param stream OUT: output stream * @param prefix NULL or a string which is written first */ -void ReHashList::dump(FILE* stream, const char* prefix) const{ +void ReHashList::dump(FILE* stream, const char* prefix) const { if (prefix != NULL) fprintf(stream, "%s\n", prefix); ReArrayPosition position; ReByteBuffer key, value; - while(next(position, &key, &value)){ - fprintf(stream, "%s : [%3d] %s\n", key.str(), value.length(), value.str()); + while (next(position, &key, &value)) { + fprintf(stream, "%s : [%3d] %s\n", key.str(), value.length(), + value.str()); } } @@ -84,7 +83,7 @@ void ReHashList::dump(FILE* stream, const char* prefix) const{ * * @return: -1: The key was not found. Otherwise: The index of the key in the key sequence array. */ -int ReHashList::find(const Byte* key, size_t length) const{ +int ReHashList::find(const Byte* key, size_t length) const { int rc = m_keys.find(key, length, NULL); return rc; } @@ -98,11 +97,11 @@ int ReHashList::find(const Byte* key, size_t length) const{ * @return false: The key was not found. true: The key was found. */ bool ReHashList::get(const Byte* key, size_t keyLength, - ReByteBuffer& value) const{ + ReByteBuffer& value) const { ReSeqArray::Index index; ReSeqArray::Tag tag; bool rc = m_keys.binarySearch(key, keyLength, index, &tag); - if (rc){ + if (rc) { m_values.get(ReSeqArray::Index(tag), value); } return rc; @@ -114,8 +113,7 @@ bool ReHashList::get(const Byte* key, size_t keyLength, * * @return false: The key was not found. true: The key was found. */ -bool ReHashList::get(const ReByteBuffer& key, - ReByteBuffer& value) const{ +bool ReHashList::get(const ReByteBuffer& key, ReByteBuffer& value) const { bool rc = get(key.str(), key.length(), value); return rc; } @@ -131,22 +129,24 @@ bool ReHashList::get(const ReByteBuffer& key, * @param true: An item was found. false: No more items. */ bool ReHashList::next(ReArrayPosition& position, ReByteBuffer* key, - ReByteBuffer* value) const{ + ReByteBuffer* value) const { bool rc = position.m_position + 1 < m_keys.count(); - if (rc){ + if (rc) { ReByteBuffer dummy; ReSeqArray::Tag tag; if (key == NULL) key = &dummy; - if (! m_keys.get(++position.m_position, *key, &tag)){ + if (!m_keys.get(++position.m_position, *key, &tag)) { globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_NEXT_1, - i18n("next(): invalid cursor: $1")) - .arg((int) position.m_position).end(); + i18n("next(): invalid cursor: $1")).arg( + (int) position.m_position).end(); } else { if (value != NULL) - if (! m_values.get((size_t) tag, *value)){ + if (!m_values.get((size_t) tag, *value)) { globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_NEXT_1, - i18n("next(): invalid content index: $1")).arg((int) tag).end(); } + i18n("next(): invalid content index: $1")).arg( + (int) tag).end(); + } } } return rc; @@ -158,15 +158,15 @@ bool ReHashList::next(ReArrayPosition& position, ReByteBuffer* key, * @param value The value byte sequence. * @param valueLength The length of value. */ -void ReHashList::put(const Byte* key, size_t keyLength, - const Byte* value, size_t valueLength){ +void ReHashList::put(const Byte* key, size_t keyLength, const Byte* value, + size_t valueLength) { ReSeqArray::Index index; ReSeqArray::Tag tag; if (keyLength == (size_t) -1) keyLength = strlen(key); if (valueLength == (size_t) -1) valueLength = strlen(value); - if (m_keys.binarySearch(key, keyLength, index, &tag)){ + if (m_keys.binarySearch(key, keyLength, index, &tag)) { // replace the value: m_values.set((ReSeqArray::Index) tag, value, valueLength, 0); } else { @@ -180,7 +180,7 @@ void ReHashList::put(const Byte* key, size_t keyLength, * @param key The key. This is a C string. * @param value The value. This is a C string. */ -void ReHashList::put(const char* key, const char* value){ +void ReHashList::put(const char* key, const char* value) { put(key, -1, value, -1); } /** @brief Puts a key value pair into the hashlist. @@ -188,7 +188,7 @@ void ReHashList::put(const char* key, const char* value){ * @param key The key. * @param value The value. */ -void ReHashList::put(const ReByteBuffer& key, const ReByteBuffer& value){ +void ReHashList::put(const ReByteBuffer& key, const ReByteBuffer& value) { put(key.str(), key.length(), value.str(), value.length()); } @@ -202,7 +202,7 @@ void ReHashList::put(const ReByteBuffer& key, const ReByteBuffer& value){ * @param valueSpace reserve the space for this amount of value string space.
* < 0: the current space will be doubled until -valueSpace */ -void ReHashList::setCapacity(int maxKeys, int keySpace, int contentSpace){ +void ReHashList::setCapacity(int maxKeys, int keySpace, int contentSpace) { m_keys.setCapacity(maxKeys, keySpace); m_values.setCapacity(maxKeys, contentSpace); } @@ -216,7 +216,7 @@ void ReHashList::setCapacity(int maxKeys, int keySpace, int contentSpace){ * 1: maximal string length = 255,
* 2: maximal string length = 64k ... */ -void ReHashList::setSizes(int sizeOfKeyString, int sizeOfValueString){ +void ReHashList::setSizes(int sizeOfKeyString, int sizeOfValueString) { m_keys.setSizes(4, sizeOfKeyString); m_values.setSizes(0, sizeOfValueString); } @@ -228,7 +228,7 @@ void ReHashList::setSizes(int sizeOfKeyString, int sizeOfValueString){ * @param prefix NULL or a prefix of the output * @return buffer.str() (for chaining) */ -const char* ReHashList::status(ReByteBuffer& buffer, const char* prefix) const{ +const char* ReHashList::status(ReByteBuffer& buffer, const char* prefix) const { if (prefix != NULL) buffer.append(prefix).append("\n", 1); m_keys.status(buffer, "keys: "); @@ -236,5 +236,3 @@ const char* ReHashList::status(ReByteBuffer& buffer, const char* prefix) const{ return buffer.str(); } - - diff --git a/base/ReHashList.hpp b/base/ReHashList.hpp index f9cb183..da7f95c 100644 --- a/base/ReHashList.hpp +++ b/base/ReHashList.hpp @@ -10,7 +10,7 @@ #ifndef REHASHLIST_H_ #define REHASHLIST_H_ -class ReArrayPosition{ +class ReArrayPosition { public: ReArrayPosition(); public: @@ -32,15 +32,17 @@ public: typedef ReSeqArray::Sequence Sequence; public: ReHashList(bool ignoreCase = false, int keyTagSize = 1, - int contentLengthSize = 1, int keyLengthSize = 1); + int contentLengthSize = 1, int keyLengthSize = 1); virtual ~ReHashList(); public: void clear(); void dump(FILE* stream, const char* prefix = NULL) const; bool get(const Byte* key, size_t keyLength, ReByteBuffer& value) const; bool get(const ReByteBuffer& key, ReByteBuffer& value) const; - bool next(ReArrayPosition& position, ReByteBuffer* key, ReByteBuffer* val) const; - void put(const Byte* key, size_t keyLength, const Byte* value, size_t valueLength); + bool next(ReArrayPosition& position, ReByteBuffer* key, + ReByteBuffer* val) const; + void put(const Byte* key, size_t keyLength, const Byte* value, + size_t valueLength); void put(const char* key, const char* value); void put(const ReByteBuffer& key, const ReByteBuffer& value); void setCapacity(int maxKeys, int keySpace, int contentSpace); diff --git a/base/ReI18N.cpp b/base/ReI18N.cpp index ac79491..8361d46 100644 --- a/base/ReI18N.cpp +++ b/base/ReI18N.cpp @@ -10,15 +10,14 @@ #include "base/rebase.hpp" //@ The current language. If NULL no language has been chosen. -ReI18N::LanguagePack* ReI18N::m_current = 0; +ReI18N::LanguagePack* ReI18N::m_current = 0; //@ An array of all available translation packages. -ReI18N::LanguagePack ReI18N::m_list[8]; +ReI18N::LanguagePack ReI18N::m_list[8]; //@ The number of available translations. -int ReI18N::m_count = 0; +int ReI18N::m_count = 0; //@ This instance will be used for convenient usage of i18nf(const char* key) //@ Because of this i18nf(const char* key) is not reentrant. -ReVarArgs ReI18N::m_varArgs; - +ReVarArgs ReI18N::m_varArgs; /** @brief Initializes the module. * @@ -32,14 +31,14 @@ ReVarArgs ReI18N::m_varArgs; */ void ReI18N::init() { static bool first = true; - if (first){ + if (first) { if (m_current == NULL) - first = false; - if (getenv("LC_MESSAGES") != NULL){ + first = false; + if (getenv("LC_MESSAGES") != NULL) { changeLanguage(getenv("LC_MESSAGES")); - } else if (getenv("LC_ALL") != NULL){ + } else if (getenv("LC_ALL") != NULL) { changeLanguage(getenv("LC_ALL")); - } else if (getenv("LANG") != NULL){ + } else if (getenv("LANG") != NULL) { changeLanguage(getenv("LANG")); } else changeLanguage("de"); @@ -62,9 +61,9 @@ void ReI18N::init() { * @param count The number of entries in translation. * @return true So it can used in an expression. */ -bool ReI18N::registerLanguage(const char* language, - const Phrase translation[], size_t count){ - if ((size_t) m_count < sizeof m_list / sizeof m_list[0]){ +bool ReI18N::registerLanguage(const char* language, const Phrase translation[], + size_t count) { + if ((size_t) m_count < sizeof m_list / sizeof m_list[0]) { LanguagePack* lang = m_list + m_count++; lang->m_language = language; lang->m_translation = translation; @@ -84,28 +83,28 @@ bool ReI18N::registerLanguage(const char* language, * * @param language The wanted language: may be xx or xx_yy* */ -void ReI18N::changeLanguage(const char* language){ +void ReI18N::changeLanguage(const char* language) { int found = -1; // Search for xx_yy* - if (strlen(language) >= 5){ - for (int ii = 0; found < 0 && ii < m_count; ii++){ + if (strlen(language) >= 5) { + for (int ii = 0; found < 0 && ii < m_count; ii++) { if (strncmp(m_list[ii].m_language, language, 5) == 0) found = ii; } } - if (found < 0){ + if (found < 0) { // Search for xx or xx.*: - for (int ii = 0; found < 0 && ii < m_count; ii++){ + for (int ii = 0; found < 0 && ii < m_count; ii++) { const char* current = m_list[ii].m_language; if (ReStringUtils::strnicmp(current, language, 2) == 0 - && (strlen(current) == 2 - || (strlen(current) > 2 && current[2] == '.'))) + && (strlen(current) == 2 + || (strlen(current) > 2 && current[2] == '.'))) found = ii; } } // Search for xx* - if (found < 0 && strlen(language) >= 5){ - for (int ii = 0; found < 0 && ii < m_count; ii++){ + if (found < 0 && strlen(language) >= 5) { + for (int ii = 0; found < 0 && ii < m_count; ii++) { if (strncmp(m_list[ii].m_language, language, 2) == 0) found = ii; } @@ -115,7 +114,7 @@ void ReI18N::changeLanguage(const char* language){ m_current = m_list + found; } -static int compare(const void* i1, const void* i2){ +static int compare(const void* i1, const void* i2) { const char* s1 = ((ReI18N::Phrase*) i1)->m_key; const char* s2 = ((ReI18N::Phrase*) i2)->m_key; return strcmp(s1, s2); @@ -130,14 +129,14 @@ static int compare(const void* i1, const void* i2){ * @return key: No translation could be found. * Otherwise: The translated key. */ -const char* ReI18N::tr(const char* key){ +const char* ReI18N::tr(const char* key) { init(); const char* rc = key; - if (m_current != NULL){ + if (m_current != NULL) { Phrase current; current.m_key = key; Phrase* found = (Phrase*) bsearch(¤t, m_current->m_translation, - m_current->m_count, sizeof (Phrase), compare); + m_current->m_count, sizeof(Phrase), compare); if (found != NULL) rc = found->m_value; } @@ -158,7 +157,7 @@ const char* ReI18N::tr(const char* key){ * * @return An variant argument instance for chaining. */ -ReVarArgs& ReI18N::trF(const char* key){ +ReVarArgs& ReI18N::trF(const char* key) { return trF(key, m_varArgs); } /** @brief Translates a string with placeholders. @@ -178,7 +177,7 @@ ReVarArgs& ReI18N::trF(const char* key){ * * @return The variant argument instance args for chaining. */ -ReVarArgs& ReI18N::trF(const char* key, ReVarArgs& args){ +ReVarArgs& ReI18N::trF(const char* key, ReVarArgs& args) { init(); // We hide the method name tr. xgettext must not see tr() #define translate tr diff --git a/base/ReI18N.hpp b/base/ReI18N.hpp index 81c1038..9003ed0 100644 --- a/base/ReI18N.hpp +++ b/base/ReI18N.hpp @@ -14,41 +14,43 @@ class ReI18N { public: //@ Storage for the ISO language names (with trailing '\\0'). - typedef struct { char m_id[3]; } Language; + typedef struct { + char m_id[3]; + } Language; typedef struct { const char* m_key; const char* m_value; } Phrase; typedef struct { - const char* m_language; - const Phrase* m_translation; - size_t m_count; + const char* m_language; + const Phrase* m_translation; + size_t m_count; } LanguagePack; public: static void init(); static bool registerLanguage(const char* language, - const Phrase translation[], size_t count); + const Phrase translation[], size_t count); static const char* tr(const char* key); static ReVarArgs& trF(const char* key); static ReVarArgs& trF(const char* key, ReVarArgs& args); static void changeLanguage(const char* language); protected: - static LanguagePack* m_current; - static LanguagePack m_list[8]; - static int m_count; - static ReVarArgs m_varArgs; + static LanguagePack* m_current; + static LanguagePack m_list[8]; + static int m_count; + static ReVarArgs m_varArgs; }; -inline const char* i18n(const char* key){ +inline const char* i18n(const char* key) { return ReI18N::tr(key); } //@ Translates a string into another language. //@ Not threadsafe, not reentrant. -inline ReVarArgs& i18nf(const char* key){ +inline ReVarArgs& i18nf(const char* key) { return ReI18N::trF(key); } //@ Translates a string into another language. //@ Threadsafe, reentrant. -inline ReVarArgs& i18nf(const char* key, ReVarArgs& args){ +inline ReVarArgs& i18nf(const char* key, ReVarArgs& args) { return ReI18N::trF(key, args); } //@ Use this macros for transformable strings in initializations of variables. diff --git a/base/ReLogger.cpp b/base/ReLogger.cpp index f222c30..7d1c1f8 100644 --- a/base/ReLogger.cpp +++ b/base/ReLogger.cpp @@ -22,8 +22,8 @@ ReLogger* ReLogger::m_globalLogger = NULL; * * @return The global logger. */ -ReLogger* ReLogger::globalLogger(){ - if (m_globalLogger == NULL){ +ReLogger* ReLogger::globalLogger() { + if (m_globalLogger == NULL) { m_globalLogger = new ReLogger(); m_globalLogger->addStandardAppenders(true, "globallogger"); } @@ -32,25 +32,23 @@ ReLogger* ReLogger::globalLogger(){ /** * Frees the resources of the global logger (if it exists). */ -void ReLogger::freeGlobalLogger(){ - if (m_globalLogger != NULL){ +void ReLogger::freeGlobalLogger() { + if (m_globalLogger != NULL) { delete m_globalLogger; m_globalLogger = NULL; } } /** @brief Constructor. */ -ReAppender::ReAppender() - : - m_errorCategories(CAT_ALL), - m_warningCategories(CAT_ALL), - m_infoCategories(CAT_ALL), - m_granularities(GRAN_ALL) -{ +ReAppender::ReAppender() : + m_errorCategories(CAT_ALL), + m_warningCategories(CAT_ALL), + m_infoCategories(CAT_ALL), + m_granularities(GRAN_ALL) { } /** @brief Destructor. */ -ReAppender::~ReAppender(){ +ReAppender::~ReAppender() { } /** Tests whether the log message should be logged. @@ -59,13 +57,12 @@ ReAppender::~ReAppender(){ * * @return true: The */ -bool ReAppender::accept(ReClassCategoryGranularity mode){ +bool ReAppender::accept(ReClassCategoryGranularity mode) { ReLogCategory category = (ReLogCategory) (mode & CAT_ALL); ReLogClass aClass = (ReLogClass) (mode & LOG_CLASS_ALL); bool rc; - switch (aClass) - { + switch (aClass) { case LOG_ERROR: case LOG_ABORT: rc = (m_errorCategories & category) != 0; @@ -73,14 +70,13 @@ bool ReAppender::accept(ReClassCategoryGranularity mode){ case LOG_WARNING: rc = (m_warningCategories & category) != 0; break; - default: - { + default: { ReLogGranularity granularity = (ReLogGranularity) (mode & GRAN_ALL); if (granularity == 0) granularity = GRAN_USER; rc = (m_infoCategories & category) != 0 - && (m_granularities & granularity) != 0; + && (m_granularities & granularity) != 0; break; } } @@ -94,7 +90,7 @@ bool ReAppender::accept(ReClassCategoryGranularity mode){ * @param granularities The granularities in which info logging will be done. */ void ReAppender::setMode(ReLogCategories errors, ReLogCategories warnings, - ReLogCategories infos, ReLogGranularities granularities){ + ReLogCategories infos, ReLogGranularities granularities) { m_errorCategories = (errors & CAT_ALL); m_warningCategories = (warnings & CAT_ALL); m_infoCategories = (infos & CAT_ALL); @@ -105,16 +101,14 @@ void ReAppender::setMode(ReLogCategories errors, ReLogCategories warnings, * * @param stream An open stream used for the output. */ -ReStreamAppender::ReStreamAppender(FILE* stream) - : - ReAppender(), - m_stream(stream) -{ +ReStreamAppender::ReStreamAppender(FILE* stream) : + ReAppender(), + m_stream(stream) { } /** @brief Destructor. */ -ReStreamAppender::~ReStreamAppender(){ - if (m_stream != NULL){ +ReStreamAppender::~ReStreamAppender() { + if (m_stream != NULL) { fclose(m_stream); m_stream = NULL; } @@ -125,34 +119,32 @@ ReStreamAppender::~ReStreamAppender(){ * @param logger The logger calling the method. * @param message The message to write. */ -void ReStreamAppender::say(ReLogger* logger, const char* message){ +void ReStreamAppender::say(ReLogger* logger, const char* message) { const char* prefix = logger->getStandardPrefix(); - if (m_stream != NULL){ - fputs(prefix, m_stream); - if (message != NULL) - fputs(message, m_stream); - else - fputs(logger->asCString(), m_stream); - fputc('\n', m_stream); - fflush(m_stream); - } + if (m_stream != NULL) { + fputs(prefix, m_stream); + if (message != NULL) + fputs(message, m_stream); + else + fputs(logger->asCString(), m_stream); + fputc('\n', m_stream); + fflush(m_stream); + } } /** @brief Constructor. */ -ReFileAppender::ReFileAppender() - : - ReStreamAppender(NULL), - //m_filePattern - m_maxFiles(10), - m_maxSize(1000000), - m_currentSize(0), - m_currentFileNo(0) -{ +ReFileAppender::ReFileAppender() : + ReStreamAppender(NULL), + //m_filePattern + m_maxFiles(10), + m_maxSize(1000000), + m_currentSize(0), + m_currentFileNo(0) { strcpy(m_filePattern, "logger.*"); } /** @brief Destructor. */ -ReFileAppender::~ReFileAppender(){ +ReFileAppender::~ReFileAppender() { } /** @brief Sets the configuration data. @@ -163,15 +155,16 @@ ReFileAppender::~ReFileAppender(){ * @param maxSize Maximum size of one logfile. * */ -void ReFileAppender::setConfig(const char* pattern, int maxFiles, int maxSize){ +void ReFileAppender::setConfig(const char* pattern, int maxFiles, int maxSize) { const char* placeholder = "%04d"; m_maxFiles = maxFiles < 2 ? 2 : maxFiles; m_maxSize = maxSize < 10 ? 10 : maxSize; const char* first = strchr(pattern, '*'); size_t len; - if (first == NULL){ - _snprintf(m_filePattern, sizeof m_filePattern, "%s.%s.log", pattern, placeholder); + if (first == NULL) { + _snprintf(m_filePattern, sizeof m_filePattern, "%s.%s.log", pattern, + placeholder); } else { len = first - pattern; memcpy(m_filePattern, pattern, len); @@ -185,9 +178,11 @@ void ReFileAppender::setConfig(const char* pattern, int maxFiles, int maxSize){ if (fn.length() == 0) fn.set(".", 1); ReDirectory dir(fn.str()); - if (! dir.isValid()){ - fprintf(stderr, "%s\n", i18nf("$1: Not a valid directory: $2").arg(pattern).arg(dir.getDir()).asCString()); - assert(! dir.isValid()); + if (!dir.isValid()) { + fprintf(stderr, "%s\n", + i18nf("$1: Not a valid directory: $2").arg(pattern).arg( + dir.getDir()).asCString()); + assert(!dir.isValid()); } else { ReStringUtils::joinPath(fn, NULL, NULL, &name, &ext); int ix = fn.indexOf(placeholder, -1, 0); @@ -198,7 +193,7 @@ void ReFileAppender::setConfig(const char* pattern, int maxFiles, int maxSize){ #endif // Looking for the current logfile: - if (! dir.findFirst(fn.str(), true)){ + if (!dir.findFirst(fn.str(), true)) { fn.splice(ix, 8, "0001", 4); m_currentFileNo = 1; } else { @@ -215,10 +210,12 @@ void ReFileAppender::setConfig(const char* pattern, int maxFiles, int maxSize){ if (rc == 0 && (m_currentSize = info.st_size) > m_maxSize) changeFile(); - else{ + else { m_stream = fopen(fullname.str(), "a"); - if (m_stream == NULL){ - fprintf (stderr, "+++ ReFileAppender::setConfig(): cannot open: '%s'\n", fullname.str()); + if (m_stream == NULL) { + fprintf(stderr, + "+++ ReFileAppender::setConfig(): cannot open: '%s'\n", + fullname.str()); //assert(m_stream != NULL); } } @@ -226,8 +223,8 @@ void ReFileAppender::setConfig(const char* pattern, int maxFiles, int maxSize){ } /** @brief Opens a new file for logging. */ -void ReFileAppender::changeFile(){ - if (m_stream != NULL){ +void ReFileAppender::changeFile() { + if (m_stream != NULL) { fclose(m_stream); m_stream = NULL; } @@ -236,8 +233,9 @@ void ReFileAppender::changeFile(){ const size_t FILENO_UBOUND = 10000; // Delete some of the oldest files to make room for the new: - for (int ii = 0; ii < int(FILENO_UBOUND - m_maxFiles); ii++){ - int fileNo = (FILENO_UBOUND + m_currentFileNo - m_maxFiles - ii) % m_maxFiles; + for (int ii = 0; ii < int(FILENO_UBOUND - m_maxFiles); ii++) { + int fileNo = (FILENO_UBOUND + m_currentFileNo - m_maxFiles - ii) + % m_maxFiles; _snprintf(filename, sizeof filename, m_filePattern, fileNo); struct stat info; if (lstat(filename, &info) == 0) @@ -253,20 +251,18 @@ void ReFileAppender::changeFile(){ } /** @brief Constructor. */ -ReLogger::ReLogger(bool isGlobal) - : - ReVarArgs(), - m_appenderList(new ReAppender* [8]), - m_appenderListSize(8), - m_appenderListLength(0), - // m_standardPrefix[64] - m_mode(0), - m_location(0), - m_stdConsoleAppender(NULL), - m_stdFileAppender(NULL), - m_locationOfOpenSayF(0) -{ - if (isGlobal){ +ReLogger::ReLogger(bool isGlobal) : + ReVarArgs(), + m_appenderList(new ReAppender*[8]), + m_appenderListSize(8), + m_appenderListLength(0), + // m_standardPrefix[64] + m_mode(0), + m_location(0), + m_stdConsoleAppender(NULL), + m_stdFileAppender(NULL), + m_locationOfOpenSayF(0) { + if (isGlobal) { delete m_globalLogger; m_globalLogger = this; } @@ -274,7 +270,7 @@ ReLogger::ReLogger(bool isGlobal) } /** @brief Destructor. */ -ReLogger::~ReLogger(){ +ReLogger::~ReLogger() { delete m_stdConsoleAppender; m_stdConsoleAppender = NULL; delete m_stdFileAppender; @@ -297,12 +293,13 @@ ReLogger::~ReLogger(){ * * @return true */ -bool ReLogger::say(ReClassCategoryGranularity mode, ReLogLocation location, const char* message){ +bool ReLogger::say(ReClassCategoryGranularity mode, ReLogLocation location, + const char* message) { m_mode = mode; m_location = location; m_standardPrefix[0] = '\0'; - for (size_t ii = 0; ii < m_appenderListLength; ii++){ + for (size_t ii = 0; ii < m_appenderListLength; ii++) { ReAppender* app = m_appenderList[ii]; if (app->accept(mode)) app->say(this, message); @@ -322,13 +319,13 @@ bool ReLogger::say(ReClassCategoryGranularity mode, ReLogLocation location, cons * * @return true */ -ReVarArgs& ReLogger::sayF(ReClassCategoryGranularity mode, ReLogLocation location, - const char* format){ - if (m_locationOfOpenSayF != 0){ +ReVarArgs& ReLogger::sayF(ReClassCategoryGranularity mode, + ReLogLocation location, const char* format) { + if (m_locationOfOpenSayF != 0) { char message[128]; - _snprintf(message, sizeof message, "missing ReLogger::end(): Location: %d", - m_locationOfOpenSayF); - say(LOG_ERROR|GRAN_USER|CAT_LIB, LC_LOGGER_SAYF_OPEN, message); + _snprintf(message, sizeof message, + "missing ReLogger::end(): Location: %d", m_locationOfOpenSayF); + say(LOG_ERROR | GRAN_USER | CAT_LIB, LC_LOGGER_SAYF_OPEN, message); } m_locationOfOpenSayF = location; m_mode = mode; @@ -338,38 +335,37 @@ ReVarArgs& ReLogger::sayF(ReClassCategoryGranularity mode, ReLogLocation locatio return *this; } /** Adds an appender to the appender list. -* -* @param appender The appender. -*/ -void ReLogger::addAppender(ReAppender* appender){ + * + * @param appender The appender. + */ +void ReLogger::addAppender(ReAppender* appender) { if (m_appenderListLength >= m_appenderListSize) - throw ReBoundsException("appender list", - m_appenderListLength + 1, m_appenderListSize, - __FILE__, __LINE__); + throw ReBoundsException("appender list", m_appenderListLength + 1, + m_appenderListSize, + __FILE__, __LINE__); m_appenderList[m_appenderListLength++] = appender; } /** Adds standard appenders to the appender list. -* -* @param console true: A console appender will be added. -* @param file NULL: No file appender. -* Otherwise: A file appender will be appended. -* @param maxFiles The maximal count of log files produced by the file appender. -* @param masSize The maximal size of one log file produced by the file appender. -*/ -void ReLogger::addStandardAppenders(bool console, - const char* file, int maxFiles, int maxSize){ - if (console){ + * + * @param console true: A console appender will be added. + * @param file NULL: No file appender. + * Otherwise: A file appender will be appended. + * @param maxFiles The maximal count of log files produced by the file appender. + * @param masSize The maximal size of one log file produced by the file appender. + */ +void ReLogger::addStandardAppenders(bool console, const char* file, + int maxFiles, int maxSize) { + if (console) { m_stdConsoleAppender = new ReStreamAppender(stdout); addAppender(m_stdConsoleAppender); } - if (file != NULL){ + if (file != NULL) { m_stdFileAppender = new ReFileAppender(); m_stdFileAppender->setConfig(file, maxFiles, maxSize); addAppender(m_stdFileAppender); } - } /** @brief Returns the standard prefix of a log line. @@ -380,11 +376,10 @@ void ReLogger::addStandardAppenders(bool console, * * @return The standard prefix. */ -const char* ReLogger::getStandardPrefix(void){ - if (m_standardPrefix[0] == 0) - { +const char* ReLogger::getStandardPrefix(void) { + if (m_standardPrefix[0] == 0) { char cc; - switch(m_mode & LOG_CLASS_ALL){ + switch (m_mode & LOG_CLASS_ALL) { case LOG_ABORT: cc = '#'; break; @@ -403,11 +398,11 @@ const char* ReLogger::getStandardPrefix(void){ time_t now = time(NULL); struct tm* now1 = localtime(&now); strftime(m_standardPrefix + 1, sizeof m_standardPrefix - 1, - "%Y.%m.%d %H:%M:%S", now1); + "%Y.%m.%d %H:%M:%S", now1); size_t len = strlen(m_standardPrefix); char* ptr = m_standardPrefix + len; - _snprintf (ptr, sizeof m_standardPrefix - len, " %ld: ", - (long) m_location); + _snprintf(ptr, sizeof m_standardPrefix - len, " %ld: ", + (long) m_location); } return m_standardPrefix; } @@ -416,8 +411,8 @@ const char* ReLogger::getStandardPrefix(void){ * This method puts the data to the (accepting) appenders. * */ -void ReLogger::end(void){ - for (size_t ii = 0; ii < m_appenderListLength; ii++){ +void ReLogger::end(void) { + for (size_t ii = 0; ii < m_appenderListLength; ii++) { ReAppender* app = m_appenderList[ii]; if (app->accept(m_mode)) app->say(this, NULL); diff --git a/base/ReLogger.hpp b/base/ReLogger.hpp index 50dfba0..4bb436d 100644 --- a/base/ReLogger.hpp +++ b/base/ReLogger.hpp @@ -18,11 +18,8 @@ typedef unsigned long int ReLogLocation; * The log messages can be divided in 4 classes: * Aborts, errors, warnings and informations. */ -enum ReLogClass{ - LOG_ABORT = 1, - LOG_ERROR = 2, - LOG_WARNING = 4, - LOG_INFO = 8, +enum ReLogClass { + LOG_ABORT = 1, LOG_ERROR = 2, LOG_WARNING = 4, LOG_INFO = 8, LOG_CLASS_ALL = 0xf }; @@ -33,35 +30,35 @@ typedef unsigned int ReSetOfClasses; /** * The granularity allows to filter log messages under the aspect of the amount. */ -enum ReLogGranularity{ - GRAN_USER = 0x00000010, - GRAN_GURU = 0x00000020, - GRAN_DUMP = 0x00000040, - GRAN_TRACE = 0x00000080, - GRAN_SPECIAL_1 = 0x00000100, - GRAN_SPECIAL_2 = 0x00000200, - GRAN_SPECIAL_3 = 0x00000400, - GRAN_SPECIAL_4 = 0x00000800, +enum ReLogGranularity { + GRAN_USER = 0x00000010, + GRAN_GURU = 0x00000020, + GRAN_DUMP = 0x00000040, + GRAN_TRACE = 0x00000080, + GRAN_SPECIAL_1 = 0x00000100, + GRAN_SPECIAL_2 = 0x00000200, + GRAN_SPECIAL_3 = 0x00000400, + GRAN_SPECIAL_4 = 0x00000800, - GRAN_ALL = 0x00000ff0 + GRAN_ALL = 0x00000ff0 }; /** A (bitwise) combination of granularities. */ typedef unsigned long int ReLogGranularities; -enum ReLogCategory{ - CAT_START_STOP = 0x00001000, - CAT_CONFIG = 0x00002000, - CAT_NETWORK = 0x00004000, - CAT_GUI = 0x00008000, - CAT_LIB = 0x00010000, - CAT_OS = 0x00020000, - CAT_FILE = 0x00040000, - CAT_PROG = 0x00080000, - CAT_RESOURCE = 0x00100000, - CAT_TEST = 0x00200000, - CAT_SECURITY = 0x00400000, +enum ReLogCategory { + CAT_START_STOP = 0x00001000, + CAT_CONFIG = 0x00002000, + CAT_NETWORK = 0x00004000, + CAT_GUI = 0x00008000, + CAT_LIB = 0x00010000, + CAT_OS = 0x00020000, + CAT_FILE = 0x00040000, + CAT_PROG = 0x00080000, + CAT_RESOURCE = 0x00100000, + CAT_TEST = 0x00200000, + CAT_SECURITY = 0x00400000, - CAT_ALL = 0xfffff000, + CAT_ALL = 0xfffff000, }; /** A (bitwise) combination of categories. */ @@ -74,7 +71,7 @@ class ReLogger; /** * Implements an abstract base class for handling of the output of an logger. */ -class ReAppender{ +class ReAppender { public: ReAppender(); virtual ~ReAppender(); @@ -82,36 +79,36 @@ public: virtual void say(ReLogger* logger, const char* message) = 0; bool accept(ReClassCategoryGranularity mode); void setMode(ReLogCategories errors, ReLogCategories warnings, - ReLogCategories infos, ReLogGranularities granularities); + ReLogCategories infos, ReLogGranularities granularities); protected: - ReLogCategories m_errorCategories; - ReLogCategories m_warningCategories; - ReLogCategories m_infoCategories; - ReLogGranularities m_granularities; + ReLogCategories m_errorCategories; + ReLogCategories m_warningCategories; + ReLogCategories m_infoCategories; + ReLogGranularities m_granularities; }; /** * Implements a class which is writing log messages to a stream. */ -class ReStreamAppender : public ReAppender{ +class ReStreamAppender: public ReAppender { public: ReStreamAppender(FILE* stream); virtual ~ReStreamAppender(); private: - // Not accessible, not implemented! + // Not accessible, not implemented! ReStreamAppender(const ReStreamAppender& source); - // Not accessible, not implemented! + // Not accessible, not implemented! ReStreamAppender& operator =(const ReStreamAppender& source); public: virtual void say(ReLogger* logger, const char* message); protected: - FILE* m_stream; + FILE* m_stream; }; /** * Implements a class which is writing log messages to a file. */ -class ReFileAppender : public ReStreamAppender { +class ReFileAppender: public ReStreamAppender { public: ReFileAppender(); virtual ~ReFileAppender(); @@ -121,11 +118,11 @@ private: void changeFile(); protected: - char m_filePattern[512]; - size_t m_maxFiles; - size_t m_maxSize; - size_t m_currentSize; - size_t m_currentFileNo; + char m_filePattern[512]; + size_t m_maxFiles; + size_t m_maxSize; + size_t m_currentSize; + size_t m_currentFileNo; }; /** This class allows the logging of messages. @@ -134,7 +131,7 @@ protected: * The message can be contain placeholders which will be replaced * by computed data similar sprintf(), but in a typesafe way (@see sayF()). */ -class ReLogger : public ReVarArgs { +class ReLogger: public ReVarArgs { public: static ReLogger* globalLogger(); static void freeGlobalLogger(); @@ -143,13 +140,15 @@ public: ReLogger(bool isGlobal = true); virtual ~ReLogger(); private: - // Not accessible, not implemented! + // Not accessible, not implemented! ReLogger(const ReLogger& source); - // Not accessible, not implemented! + // Not accessible, not implemented! ReLogger& operator =(const ReLogger& source); public: - bool say(ReClassCategoryGranularity mode, ReLogLocation location, const char* message); - ReVarArgs& sayF(ReClassCategoryGranularity mode, ReLogLocation location, const char* format); + bool say(ReClassCategoryGranularity mode, ReLogLocation location, + const char* message); + ReVarArgs& sayF(ReClassCategoryGranularity mode, ReLogLocation location, + const char* format); virtual void end(void); void addAppender(ReAppender* appender); @@ -157,18 +156,18 @@ public: const char* getStandardPrefix(void); ReClassCategoryGranularity getCurrentMode(void) const; int getCurrentPosition(void) const; - void addStandardAppenders(bool console, const char* file, - int fileCount = 5, int fileSize = 1000100); + void addStandardAppenders(bool console, const char* file, int fileCount = 5, + int fileSize = 1000100); protected: - ReAppender** m_appenderList; - size_t m_appenderListSize; - size_t m_appenderListLength; - char m_standardPrefix[64]; + ReAppender** m_appenderList; + size_t m_appenderListSize; + size_t m_appenderListLength; + char m_standardPrefix[64]; ReClassCategoryGranularity m_mode; - ReLogLocation m_location; - ReAppender* m_stdConsoleAppender; - ReFileAppender* m_stdFileAppender; - int m_locationOfOpenSayF; + ReLogLocation m_location; + ReAppender* m_stdConsoleAppender; + ReFileAppender* m_stdFileAppender; + int m_locationOfOpenSayF; }; inline ReLogger* globalLogger() { diff --git a/base/ReProgramArgs.cpp b/base/ReProgramArgs.cpp index 139a9d6..9280034 100644 --- a/base/ReProgramArgs.cpp +++ b/base/ReProgramArgs.cpp @@ -19,19 +19,17 @@ const char* ReProgramArgs::PREFIX_LINE_OPTION = " "; * @param arg2 The 2nd argument (for the 2nd placeholder). * If NULL only one placeholder exists. * @throws ReFormatException -*/ + */ ReOptionException::ReOptionException(ReProgramArgs* caller, const char* message, - const char* arg1, const char* arg2) - : - ReException() -{ + const char* arg1, const char* arg2) : + ReException() { ReVarArgs args(message); - if (strchr(message, '$') == NULL) - throw ReFormatException(i18n("Missing placeholder: "), message); + if (strchr(message, '$') == NULL) + throw ReFormatException(i18n("Missing placeholder: "), message); args.arg(arg1); if (arg2 != NULL) args.arg(arg2); - setMessage(args.asCString()); + setMessage(args.asCString()); if (caller != NULL) caller->setLastError(args.asCString()); } @@ -41,30 +39,28 @@ ReOptionException::ReOptionException(ReProgramArgs* caller, const char* message, * @param usage A string array with the description of the usage. * Every string will be issued in a separate line. * @param examples A string with one ore more calling examples. -* Every string will be issued in a separate line. -*/ -ReProgramArgs::ReProgramArgs(const char* usageList[], const char* examples[]) - : - m_usage(), - m_examples(), - m_properties(false, 2, 2, 1), - m_values(), - m_args(NULL), - m_argCount(0), - m_lastError() -{ - m_properties.setCapacity(64, 64*8, 64*1024); + * Every string will be issued in a separate line. + */ +ReProgramArgs::ReProgramArgs(const char* usageList[], const char* examples[]) : + m_usage(), + m_examples(), + m_properties(false, 2, 2, 1), + m_values(), + m_args(NULL), + m_argCount(0), + m_lastError() { + m_properties.setCapacity(64, 64 * 8, 64 * 1024); ReByteBuffer line; - for (const char** argv = usageList; *argv != NULL; argv++){ + for (const char** argv = usageList; *argv != NULL; argv++) { line.set(*argv); line.removeLastChar('\n'); m_usage.append(line.str()); } - if (examples != NULL){ - for (const char** argv = examples; *argv != NULL; argv++){ + if (examples != NULL) { + for (const char** argv = examples; *argv != NULL; argv++) { if (strncmp(*argv, "$0", 2) != 0) m_examples.append(*argv); - else{ + else { ReByteBuffer line; line.append(m_program, -1); m_examples.append(line.str() + 2); @@ -79,24 +75,22 @@ ReProgramArgs::ReProgramArgs(const char* usageList[], const char* examples[]) * It may contain '\\n' for separate lines. * @param examples A string with one ore more calling examples. * It may contain '\\n' for separate lines. -*/ -ReProgramArgs::ReProgramArgs(const char* usageString, const char* examples) - : - m_usage(), - m_examples(), - m_properties(), - m_values(), - m_args(NULL), - m_argCount(0), - m_program("?"), - m_lastError() -{ + */ +ReProgramArgs::ReProgramArgs(const char* usageString, const char* examples) : + m_usage(), + m_examples(), + m_properties(), + m_values(), + m_args(NULL), + m_argCount(0), + m_program("?"), + m_lastError() { m_values.setSizes(1, 2); m_usage.split(usageString, '\n'); - if (examples != NULL){ + if (examples != NULL) { if (strstr(examples, "$0") == NULL) m_examples.split(examples, '\n'); - else{ + else { ReByteBuffer line; line.append(examples, -1); line.replaceAll("$0", 2, m_program, -1); @@ -115,10 +109,10 @@ ReProgramArgs::~ReProgramArgs() { * * @param usage a vector of lines without '\n' */ -void ReProgramArgs::setUsage(const char* usage[]){ - m_usage.clear(); - for (int ix = 0; usage[ix] != NULL; ix++) - m_usage.append(usage[ix]); +void ReProgramArgs::setUsage(const char* usage[]) { + m_usage.clear(); + for (int ix = 0; usage[ix] != NULL; ix++) + m_usage.append(usage[ix]); } /** @brief Puts the property infos into the property string. * @@ -133,19 +127,20 @@ void ReProgramArgs::setUsage(const char* usage[]){ * @param defaultValue The default value of the option. * @param lengthValue The length of defaultValue. */ -void ReProgramArgs::addProperties(const char*name, const char* description, char shortOpt, - const char* longOpt, DataType dataType, const char* defaultValue, size_t lengthValue){ +void ReProgramArgs::addProperties(const char*name, const char* description, + char shortOpt, const char* longOpt, DataType dataType, + const char* defaultValue, size_t lengthValue) { ReByteBuffer properties; - ReByteBuffer descr(description, -1); - ReByteBuffer replacement("\n", 1); - replacement.append(PREFIX_LINE_OPTION); - descr.replaceAll("\n", 1, replacement.str(), replacement.length()); + ReByteBuffer descr(description, -1); + ReByteBuffer replacement("\n", 1); + replacement.append(PREFIX_LINE_OPTION); + descr.replaceAll("\n", 1, replacement.str(), replacement.length()); properties.append(descr).appendChar('\1'); properties.append(&shortOpt, 1).appendChar('\1'); properties.append(longOpt, strlen(longOpt)).appendChar('\1'); properties.append((char*) &dataType, 1).appendChar('\1'); - properties.append(defaultValue == NULL ? "" : defaultValue, - lengthValue).appendChar('\1'); + properties.append(defaultValue == NULL ? "" : defaultValue, lengthValue) + .appendChar('\1'); m_properties.put(name, properties.str()); // Mark current value as default: @@ -171,11 +166,11 @@ static const int IxDefault = 4; * * @see getInt() */ void ReProgramArgs::addInt(const char* name, const char* description, - char shortOpt, const char* longOpt, int defaultVal){ + char shortOpt, const char* longOpt, int defaultVal) { ReByteBuffer number; number.appendInt(defaultVal); - addProperties(name, description, shortOpt, longOpt, DT_INT, - number.str(), number.length()); + addProperties(name, description, shortOpt, longOpt, DT_INT, number.str(), + number.length()); } /** @brief Adds an option with a boolean value. @@ -189,9 +184,9 @@ void ReProgramArgs::addInt(const char* name, const char* description, * @see getBool() */ void ReProgramArgs::addBool(const char* name, const char* description, - char shortOpt, const char* longOpt, bool defaultVal){ + char shortOpt, const char* longOpt, bool defaultVal) { addProperties(name, description, shortOpt, longOpt, DT_BOOL, - defaultVal ? "t" : "f", 1); + defaultVal ? "t" : "f", 1); } /** @brief Adds an option with a string value. @@ -205,10 +200,11 @@ void ReProgramArgs::addBool(const char* name, const char* description, * @see getString() */ void ReProgramArgs::addString(const char* name, const char* description, - char shortOpt, const char* longOpt, bool mayBeEmpty, const char* defaultVal){ + char shortOpt, const char* longOpt, bool mayBeEmpty, + const char* defaultVal) { addProperties(name, description, shortOpt, longOpt, - mayBeEmpty ? DT_STRING_EMPTY : DT_STRING, - defaultVal, defaultVal == NULL ? 0 : strlen(defaultVal)); + mayBeEmpty ? DT_STRING_EMPTY : DT_STRING, defaultVal, + defaultVal == NULL ? 0 : strlen(defaultVal)); } /** @brief Returns the value of a boolean option. @@ -223,13 +219,14 @@ bool ReProgramArgs::getBool(const char* name) { ReStringList properties(512, 1024, 2, 2); ReByteBuffer buffer; ReVarArgs args; - if (! m_properties.get(name, -1, buffer)) + if (!m_properties.get(name, -1, buffer)) throw ReOptionException(this, i18n("$1 is not an option name"), name); properties.split(buffer.str(), '\1'); if (properties.strOf(IxType)[0] != 'b') - throw ReOptionException(this, i18n("$1 is not an boolean option. Type is $2"), name, - properties.strOf(IxType)); + throw ReOptionException(this, + i18n("$1 is not an boolean option. Type is $2"), name, + properties.strOf(IxType)); m_values.get(name, -1, buffer); bool rc = buffer.at(1) == 't'; @@ -248,13 +245,14 @@ int ReProgramArgs::getInt(const char* name) { ReStringList properties(512, 1024, 2, 2); ReByteBuffer buffer; ReVarArgs args; - if (! m_properties.get(name, -1, buffer)) + if (!m_properties.get(name, -1, buffer)) throw ReOptionException(this, i18n("$1 is not an option name"), name); properties.split(buffer.str(), '\1'); if (properties.strOf(IxType)[0] != DT_INT) - throw ReOptionException(this, i18n("$1 is not an integer option. Type is $2"), name, - properties.strOf(IxType)); + throw ReOptionException(this, + i18n("$1 is not an integer option. Type is $2"), name, + properties.strOf(IxType)); m_values.get(name, -1, buffer); int rc = buffer.atoi(1); @@ -272,17 +270,18 @@ int ReProgramArgs::getInt(const char* name) { const char* ReProgramArgs::getString(const char* name, ReByteBuffer& buffer) { ReStringList properties(512, 1024, 2, 2); ReVarArgs args; - if (! m_properties.get(name, strlen(name), buffer)) + if (!m_properties.get(name, strlen(name), buffer)) throw ReOptionException(this, i18n("$1 is not an option name"), name); properties.split(buffer.str(), '\1'); DataType dataType = (DataType) properties.strOf(IxType)[0]; if (dataType != DT_STRING && dataType != DT_STRING_EMPTY) - throw ReOptionException(this, i18n("$1 is not a string option. Type is $2"), name, - properties.strOf(IxType)); + throw ReOptionException(this, + i18n("$1 is not a string option. Type is $2"), name, + properties.strOf(IxType)); m_values.get(name, -1, buffer); - buffer.remove(0, 1); + buffer.remove(0, 1); const char* rc = buffer.buffer(); return rc; } @@ -291,7 +290,7 @@ const char* ReProgramArgs::getString(const char* name, ReByteBuffer& buffer) { * * @return The count of arguments. */ -int ReProgramArgs::getArgCount() const{ +int ReProgramArgs::getArgCount() const { return m_argCount; } @@ -301,7 +300,7 @@ int ReProgramArgs::getArgCount() const{ * * @return NULL: Wrong index. Otherwise: The wanted argument. */ -const char* ReProgramArgs::getArg(size_t index) const{ +const char* ReProgramArgs::getArg(size_t index) const { const char* rc = NULL; if (index < (size_t) m_argCount) @@ -312,7 +311,7 @@ const char* ReProgramArgs::getArg(size_t index) const{ * * @return The name of the application. */ -const char* ReProgramArgs::getProgramName() const{ +const char* ReProgramArgs::getProgramName() const { return m_program; } @@ -326,28 +325,30 @@ const char* ReProgramArgs::getProgramName() const{ * @throws ReOptionException Unknown option. */ void ReProgramArgs::search(char shortName, const char* longName, - ReByteBuffer& name, ReStringList& list){ + ReByteBuffer& name, ReStringList& list) { ReArrayPosition position; ReByteBuffer properties; bool found = false; size_t lengthLongName = 0; - if (longName != NULL){ + if (longName != NULL) { const char* ptr; - if ( (ptr = strchr(longName, '=')) != NULL) + if ((ptr = strchr(longName, '=')) != NULL) lengthLongName = ptr - longName; else lengthLongName = strlen(longName); } - while (! found && m_properties.next(position, &name, &properties)){ + while (!found && m_properties.next(position, &name, &properties)) { const char* ptr = properties.str(); list.split(properties.str(), '\1'); - if (longName == NULL && list.count() > IxShort && shortName == list.strOf(IxShort)[0]) + if (longName == NULL && list.count() > IxShort + && shortName == list.strOf(IxShort)[0]) found = true; - else if (lengthLongName > 0 && list.count() > IxLong && list.sizeOf(IxLong) == lengthLongName + 1 - && strncmp(longName, list.strOf(IxLong), lengthLongName) == 0) + else if (lengthLongName > 0 && list.count() > IxLong + && list.sizeOf(IxLong) == lengthLongName + 1 + && strncmp(longName, list.strOf(IxLong), lengthLongName) == 0) found = true; } - if (! found){ + if (!found) { if (longName == NULL) name.set(&shortName, 1); else @@ -361,16 +362,19 @@ void ReProgramArgs::search(char shortName, const char* longName, * @param value The option's value. * @param dataType Theo option's data type. */ -void ReProgramArgs::setValue(const char* name, const char* value, const char* dataType){ - switch(dataType[0]){ +void ReProgramArgs::setValue(const char* name, const char* value, + const char* dataType) { + switch (dataType[0]) { case DT_INT: if (strspn(value, "01234567890") != strlen(value)) - throw ReOptionException(this, i18n("Option $1 expect an integer as parameter, not $2"), - name, value); + throw ReOptionException(this, + i18n("Option $1 expect an integer as parameter, not $2"), name, + value); break; case DT_STRING: if (value[0] == '\0') - throw ReOptionException(this, i18n("Option $1: Empty parameter is not allowed"), name); + throw ReOptionException(this, + i18n("Option $1: Empty parameter is not allowed"), name); break; case DT_STRING_EMPTY: case DT_BOOL: @@ -399,7 +403,7 @@ void ReProgramArgs::setValue(const char* name, const char* value, const char* da * @return true a second word has been used: It was a parameter of an string or integer option. * false: The next argument has not been used. */ -bool ReProgramArgs::analyseShort(const char* opt, const char* nextArg){ +bool ReProgramArgs::analyseShort(const char* opt, const char* nextArg) { bool rc = false; ReStringList properties(512, 1024, 2, 2); bool again; @@ -412,37 +416,38 @@ bool ReProgramArgs::analyseShort(const char* opt, const char* nextArg){ const char* nameStr = name.str(); // Forget the option short name: opt++; - switch (dataType[0]){ + switch (dataType[0]) { case DT_INT: case DT_STRING: case DT_STRING_EMPTY: - if (opt[0] != '\0'){ + if (opt[0] != '\0') { setValue(nameStr, opt, dataType); } else { - if (nextArg == NULL || nextArg[0] == '-'){ + if (nextArg == NULL || nextArg[0] == '-') { if (dataType[0] == DT_STRING_EMPTY) setValue(nameStr, "", dataType); else - throw ReOptionException(this, i18n("Option $1 has type $2! There is no parameter."), - nameStr, dataType); + throw ReOptionException(this, + i18n( + "Option $1 has type $2! There is no parameter."), + nameStr, dataType); } else { setValue(nameStr, nextArg, dataType); rc = true; } } break; - case DT_BOOL: - { + case DT_BOOL: { // Get the current value: const char* value = "t"; - if (opt[0] == '-'){ + if (opt[0] == '-') { opt++; value = "f"; } else if (opt[0] == '+') opt++; // Invert the default value: if (properties.strOf(IxDefault)[0] == 't') - value = value[0] =='t' ? "f" : "t"; + value = value[0] == 't' ? "f" : "t"; setValue(nameStr, value, dataType); again = opt[0] != '\0'; break; @@ -459,8 +464,8 @@ bool ReProgramArgs::analyseShort(const char* opt, const char* nextArg){ * * @param opt The option string without --. * - */ -void ReProgramArgs::analyseLong(const char* opt){ + */ +void ReProgramArgs::analyseLong(const char* opt) { ReStringList properties(512, 1024, 2, 2); ReByteBuffer name; search('\0', opt, name, properties); @@ -471,18 +476,20 @@ void ReProgramArgs::analyseLong(const char* opt){ if (value != NULL) value++; - switch(dataType[0]){ + switch (dataType[0]) { case DT_INT: if (value == NULL) - throw ReOptionException(this, i18n("Option $1: parameter expected. Use --$2=number"), - nameStr, nameStr); + throw ReOptionException(this, + i18n("Option $1: parameter expected. Use --$2=number"), nameStr, + nameStr); else setValue(nameStr, value, dataType); break; case DT_STRING: if (value == NULL) - throw ReOptionException(this, i18n("Option $1: parameter expected. Use --$2=string"), - nameStr, nameStr); + throw ReOptionException(this, + i18n("Option $1: parameter expected. Use --$2=string"), nameStr, + nameStr); setValue(nameStr, value, dataType); break; case DT_STRING_EMPTY: @@ -490,19 +497,20 @@ void ReProgramArgs::analyseLong(const char* opt){ value = ""; setValue(nameStr, value, dataType); break; - case DT_BOOL: - { + case DT_BOOL: { const char* boolValue = "f"; - if (value == NULL || ReStringUtils::isInList(value, - ReConfigFile::m_trueValues, true, ReStringUtils::AUTO_SEPARATOR)) + if (value == NULL + || ReStringUtils::isInList(value, ReConfigFile::m_trueValues, true, + ReStringUtils::AUTO_SEPARATOR)) boolValue = "t"; - else if (! ReStringUtils::isInList(value, ReConfigFile::m_falseValues, - true, ReStringUtils::AUTO_SEPARATOR)) - throw ReOptionException(this, i18n("Option $1: Not a boolean value: $2. Use true or false"), - nameStr, value); + else if (!ReStringUtils::isInList(value, ReConfigFile::m_falseValues, + true, ReStringUtils::AUTO_SEPARATOR)) + throw ReOptionException(this, + i18n("Option $1: Not a boolean value: $2. Use true or false"), + nameStr, value); // Invert the default value: if (properties.strOf(IxDefault)[0] == 't') - boolValue = boolValue[0] =='t' ? "f" : "t"; + boolValue = boolValue[0] == 't' ? "f" : "t"; setValue(nameStr, boolValue, dataType); break; } @@ -520,15 +528,15 @@ void ReProgramArgs::analyseLong(const char* opt){ * * @throws ReException */ -void ReProgramArgs::init(int argc, const char* argv[]){ +void ReProgramArgs::init(int argc, const char* argv[]) { m_program = argv[0]; argv++; argc--; - while (argc > 0 && argv[0][0] == '-'){ + while (argc > 0 && argv[0][0] == '-') { if (argv[0][1] == '-') analyseLong(argv[0] + 2); - else{ + else { if (analyseShort(argv[0] + 1, argc <= 1 ? NULL : argv[1])) argc--, argv++; } @@ -542,17 +550,17 @@ void ReProgramArgs::init(int argc, const char* argv[]){ * * @param message The error message. */ -void ReProgramArgs::setLastError(const char* message){ +void ReProgramArgs::setLastError(const char* message) { m_lastError.set(message, -1); } void ReProgramArgs::help(const char* message, bool issueLastError, - ReStringList& lines) const{ + ReStringList& lines) const { lines.append(m_usage); lines.append(""); ReArrayPosition position; - if (m_properties.next(position, NULL, NULL)){ + if (m_properties.next(position, NULL, NULL)) { lines.append(i18n(":")); } ReByteBuffer name; @@ -560,14 +568,14 @@ void ReProgramArgs::help(const char* message, bool issueLastError, ReByteBuffer line; ReByteBuffer param; - while(m_properties.next(position, &name, &prop)){ + while (m_properties.next(position, &name, &prop)) { ReStringList properties(512, 1024, 2, 2); properties.split(prop.str(), '\1'); line.setLength(0); DataType dataType = DataType(properties.strOf(IxType)[0]); const char* shortName = properties.strOf(IxShort); param.setLength(0); - switch(dataType){ + switch (dataType) { case DT_INT: param.append(i18n(""), -1); break; @@ -580,45 +588,48 @@ void ReProgramArgs::help(const char* message, bool issueLastError, default: break; } - if (shortName[0] != HIDDEN_SHORT_NAME){ + if (shortName[0] != HIDDEN_SHORT_NAME) { line.append("-", 1).append(shortName, 1); - line.append(param.str(), -1).appendChar(' ').append(i18n(" or "), -1); + line.append(param.str(), -1).appendChar(' ').append(i18n(" or "), + -1); } line.append(i18n("--"), -1).append(properties.strOf(IxLong), -1); - if (param.length() > 0){ + if (param.length() > 0) { line.append("=", -1).append(param.str(), -1); - if (dataType != DT_STRING || properties.strLengthOf(IxDefault) > 0){ + if (dataType != DT_STRING + || properties.strLengthOf(IxDefault) > 0) { line.append(i18n(" Default value: "), -1); - if (dataType == DT_STRING) - line.appendChar('\''); - line.append(properties.strOf(IxDefault), -1); - if (dataType == DT_STRING) - line.appendChar('\''); - } - } + if (dataType == DT_STRING) + line.appendChar('\''); + line.append(properties.strOf(IxDefault), -1); + if (dataType == DT_STRING) + line.appendChar('\''); + } + } lines.append(line.str()); line.set(PREFIX_LINE_OPTION, -1).append(properties.strOf(IxDescr), -1); lines.append(line.str()); } - if (m_examples.count() > 0){ + if (m_examples.count() > 0) { lines.append(i18n("Example(s):")); lines.append(m_examples); } - if (issueLastError && m_lastError.length() > 0){ + if (issueLastError && m_lastError.length() > 0) { line.set("+++ ", 4).append(m_lastError.str(), -1); lines.append(line.str()); } - if (message != NULL && message[0] != '\0'){ + if (message != NULL && message[0] != '\0') { line.set("+++ ", 4).append(message, -1); lines.append(line.str()); } } -void ReProgramArgs::help(const char* message, bool issueLastError, FILE* stream) const{ +void ReProgramArgs::help(const char* message, bool issueLastError, + FILE* stream) const { ReStringList lines(512, 1024, 8, 2); help(message, issueLastError, lines); - for(size_t ii = 0; ii < lines.count(); ii++){ + for (size_t ii = 0; ii < lines.count(); ii++) { fputs(lines.strOf(ii), stream); fputc('\n', stream); } diff --git a/base/ReProgramArgs.hpp b/base/ReProgramArgs.hpp index 954eec4..72836b1 100644 --- a/base/ReProgramArgs.hpp +++ b/base/ReProgramArgs.hpp @@ -13,10 +13,10 @@ class ReProgramArgs; /** All errors will reported by this exception. */ -class ReOptionException : public ReException{ +class ReOptionException: public ReException { public: ReOptionException(ReProgramArgs* caller, const char* message, - const char* arg1, const char* arg2 = NULL); + const char* arg1, const char* arg2 = NULL); }; /** @@ -37,7 +37,7 @@ public: *

The connection between definition and retrieval are names.

*/ class ReProgramArgs { - static const char* PREFIX_LINE_OPTION; + static const char* PREFIX_LINE_OPTION; public: enum DataType { DT_UNDEF = 0, @@ -54,13 +54,12 @@ public: ReProgramArgs(const char* usageString, const char* examples = NULL); virtual ~ReProgramArgs(); public: - void addInt(const char* name, const char* description, - char shortOpt, const char* longOpt, int defaultVal); - void addBool(const char* name, const char* description, - char shortOpt, const char* longOpt, bool defaultVal); - void addString(const char* name, const char* description, - char shortOpt, const char* longOpt, bool mayBeEmpty, - const char* defaultVal); + void addInt(const char* name, const char* description, char shortOpt, + const char* longOpt, int defaultVal); + void addBool(const char* name, const char* description, char shortOpt, + const char* longOpt, bool defaultVal); + void addString(const char* name, const char* description, char shortOpt, + const char* longOpt, bool mayBeEmpty, const char* defaultVal); bool getBool(const char* name); int getInt(const char* name); @@ -73,26 +72,29 @@ public: void init(int argc, const char* argv[]); void setLastError(const char* message); - void help(const char* message, bool issueLastError, ReStringList& lines) const; + void help(const char* message, bool issueLastError, + ReStringList& lines) const; void help(const char* message, bool issueLastError, FILE* stream) const; - void setUsage(const char* usage[]); + void setUsage(const char* usage[]); private: void addProperties(const char*name, const char* description, char shortOpt, - const char* longOpt, DataType dataType, const char* defaultValue, size_t lengthValue); - void search(char shortName, const char* longName, ReByteBuffer& name, ReStringList& list); + const char* longOpt, DataType dataType, const char* defaultValue, + size_t lengthValue); + void search(char shortName, const char* longName, ReByteBuffer& name, + ReStringList& list); void setValue(const char* name, const char* value, const char* dataType); bool analyseShort(const char* opt, const char* nextArg); void analyseLong(const char* opt); protected: - ReStringList m_usage; - ReStringList m_examples; - ReHashList m_properties; - ReHashList m_values; - const char** m_args; - int m_argCount; - const char* m_program; - ReByteBuffer m_lastError; + ReStringList m_usage; + ReStringList m_examples; + ReHashList m_properties; + ReHashList m_values; + const char** m_args; + int m_argCount; + const char* m_program; + ReByteBuffer m_lastError; }; #endif /* REPROGRAMARGS_H_ */ diff --git a/base/ReSeqArray.cpp b/base/ReSeqArray.cpp index 4b66e3f..1f8df44 100644 --- a/base/ReSeqArray.cpp +++ b/base/ReSeqArray.cpp @@ -10,7 +10,7 @@ #include "base/rebase.hpp" enum RELOC_SEQARRAY { - LC_SET_SIZES_1 = LC_SEQARRAY + 1, // 50201 + LC_SET_SIZES_1 = LC_SEQARRAY + 1, // 50201 LC_SET_SIZES_2, // 50202 LC_SET_SIZES_3, // 50203 LC_SET_SEQ_1, // 50204 @@ -63,19 +63,18 @@ enum RELOC_SEQARRAY { * this amount of bytes is the minimum to reserve. */ ReSeqArray::ReSeqArray(int deltaList, int deltaBuffer) : - m_content(deltaBuffer), - m_list(deltaList), - m_lost(0), - m_entrySize(sizeof(Index) + 1 + sizeof (void*)), - m_commonSize(INDIVIDUAL_SIZE), - m_sizeOfTag(sizeof (void*)), - m_sizeOfLength(1), - m_offsetOfTag(sizeof(Index) + 1), - m_offsetOfLength(sizeof(Index)), - m_sorted(false), - m_ignoreCase(false), - m_age(0) -{ + m_content(deltaBuffer), + m_list(deltaList), + m_lost(0), + m_entrySize(sizeof(Index) + 1 + sizeof(void*)), + m_commonSize(INDIVIDUAL_SIZE), + m_sizeOfTag(sizeof(void*)), + m_sizeOfLength(1), + m_offsetOfTag(sizeof(Index) + 1), + m_offsetOfLength(sizeof(Index)), + m_sorted(false), + m_ignoreCase(false), + m_age(0) { } /** @brief Destructor. */ @@ -85,21 +84,19 @@ ReSeqArray::~ReSeqArray() { * * @param source This instance will be copied. */ -ReSeqArray::ReSeqArray(const ReSeqArray& source) - : - m_content(source.m_content), - m_list(source.m_list), - m_lost(source.m_lost), - m_entrySize(source.m_entrySize), - m_commonSize(source.m_commonSize), - m_sizeOfTag(source.m_sizeOfTag), - m_sizeOfLength(source.m_sizeOfLength), - m_offsetOfTag(source.m_offsetOfTag), - m_offsetOfLength(source.m_offsetOfLength), - m_sorted(source.m_sorted), - m_ignoreCase(false), - m_age(0) -{ +ReSeqArray::ReSeqArray(const ReSeqArray& source) : + m_content(source.m_content), + m_list(source.m_list), + m_lost(source.m_lost), + m_entrySize(source.m_entrySize), + m_commonSize(source.m_commonSize), + m_sizeOfTag(source.m_sizeOfTag), + m_sizeOfLength(source.m_sizeOfLength), + m_offsetOfTag(source.m_offsetOfTag), + m_offsetOfLength(source.m_offsetOfLength), + m_sorted(source.m_sorted), + m_ignoreCase(false), + m_age(0) { } /** @brief Assignment operator. * @@ -107,7 +104,7 @@ ReSeqArray::ReSeqArray(const ReSeqArray& source) * * @result The instance itself. */ -ReSeqArray& ReSeqArray::operator = (const ReSeqArray& source){ +ReSeqArray& ReSeqArray::operator =(const ReSeqArray& source) { m_content = source.m_content; m_list = source.m_list; m_lost = source.m_lost; @@ -134,7 +131,7 @@ ReSeqArray& ReSeqArray::operator = (const ReSeqArray& source){ * @return the index of the element */ ReSeqArray::Index ReSeqArray::add(Index index, const Byte* source, - size_t sourceLength, Tag tag){ + size_t sourceLength, Tag tag) { if (sourceLength == (size_t) -1) sourceLength = strlen(source); Sequence seq; @@ -142,14 +139,14 @@ ReSeqArray::Index ReSeqArray::add(Index index, const Byte* source, m_content.append(source, sourceLength); Index rc = index; m_age++; - if (m_sorted && index == (Index) -1){ + if (m_sorted && index == (Index) -1) { binarySearch(source, sourceLength, rc); m_list.insert(rc * m_entrySize, (Byte*) &seq, m_entrySize); } else { - if (index >= count()){ + if (index >= count()) { rc = count(); m_list.append((Byte*) &seq, m_entrySize); - }else{ + } else { m_list.insert(index * m_entrySize, (Byte*) &seq, m_entrySize); } } @@ -168,49 +165,50 @@ ReSeqArray::Index ReSeqArray::add(Index index, const Byte* source, * @return -1: the key has been found. */ bool ReSeqArray::binarySearch(const Byte* toFind, int length, Index& index, - Tag* tag) const -{ + Tag* tag) const { assert(m_sorted); if (length < 0) length = strlen(toFind); bool rc = false; int lbound = 0; int theCount = count(); - int ubound = theCount - 1; + int ubound = theCount - 1; int compareRc = 0; - // binary search over the sorted vector: - while(lbound <= ubound){ - int half = (ubound + lbound) / 2; - const Sequence* seq = reinterpret_cast( - m_list.str() + half * m_entrySize); - int currentLength = getLength(seq); + // binary search over the sorted vector: + while (lbound <= ubound) { + int half = (ubound + lbound) / 2; + const Sequence* seq = reinterpret_cast(m_list.str() + + half * m_entrySize); + int currentLength = getLength(seq); int minLength = currentLength < length ? currentLength : length; const char* current = m_content.str() + seq->m_index; - compareRc = m_ignoreCase - ? _memicmp(toFind, current, minLength) - : _memcmp(toFind, current, minLength); - if (compareRc == 0 && currentLength != length) - compareRc = currentLength > length ? -1 : 1; - if (compareRc < 0) - ubound = half - 1; - else if (compareRc > 0) - lbound = half + 1; - else { + compareRc = + m_ignoreCase ? + _memicmp(toFind, current, minLength) : + _memcmp(toFind, current, minLength); + if (compareRc == 0 && currentLength != length) + compareRc = currentLength > length ? -1 : 1; + if (compareRc < 0) + ubound = half - 1; + else if (compareRc > 0) + lbound = half + 1; + else { rc = true; - index = half; + index = half; if (tag != NULL) getLengthAndTag(seq, *tag); - break; - } - } - if (! rc) - index = ubound > lbound ? ubound : lbound > theCount ? theCount : lbound; - return rc; + break; + } + } + if (!rc) + index = ubound > lbound ? ubound : + lbound > theCount ? theCount : lbound; + return rc; } /** @brief Deletes all entries in the list. */ -void ReSeqArray::clear(){ +void ReSeqArray::clear() { m_content.setLength(0); m_list.setLength(0); m_age++; @@ -225,17 +223,18 @@ void ReSeqArray::clear(){ * < 0: element1 < element2
* > 0: element1 > element2 */ -int ReSeqArray::compare(Index index1, Index index2){ +int ReSeqArray::compare(Index index1, Index index2) { Sequence* seq1 = getInfo(index1); Sequence* seq2 = getInfo(index2); size_t length1 = getLength(seq1); size_t length2 = getLength(seq2); int minLength = length1 < length2 ? length1 : length2; - int rc = m_ignoreCase - ? _memicmp(m_content.str() + seq1->m_index, - m_content.str() + seq2->m_index, minLength) - : _memcmp(m_content.str() + seq1->m_index, - m_content.str() + seq2->m_index, minLength); + int rc = + m_ignoreCase ? + _memicmp(m_content.str() + seq1->m_index, + m_content.str() + seq2->m_index, minLength) : + _memcmp(m_content.str() + seq1->m_index, + m_content.str() + seq2->m_index, minLength); if (rc == 0 && length1 != length2) rc = length1 < length2 ? -1 : 1; return rc; @@ -246,15 +245,15 @@ int ReSeqArray::compare(Index index1, Index index2){ * @param fp target file pointer * @param prefix NULL or a introduction */ -void ReSeqArray::dump(FILE* fp, const char* prefix) const{ +void ReSeqArray::dump(FILE* fp, const char* prefix) const { ReByteBuffer buffer; Tag tag; if (prefix != NULL) fprintf(fp, "%s\n", prefix); - for (int ix = 0; ix < (int) count(); ix++){ + for (int ix = 0; ix < (int) count(); ix++) { get(ix, buffer, &tag); - fprintf(fp, "%d: (%ld) [%d] %s\n", ix, (int64_t) tag, (int) buffer.length(), - buffer.str()); + fprintf(fp, "%d: (%ld) [%d] %s\n", ix, (int64_t) tag, + (int) buffer.length(), buffer.str()); } } @@ -266,21 +265,23 @@ void ReSeqArray::dump(FILE* fp, const char* prefix) const{ * @return: -1: The key was not found. Otherwise: The index of the key in the key sequence array. */ ReSeqArray::Index ReSeqArray::find(const Byte* toFind, size_t length, - Tag* tag) const{ + Tag* tag) const { if (length == (size_t) -1) length = strlen(toFind); int rc = -1; int theCount = count(); - for (int ix = 0; ix < theCount; ix++){ + for (int ix = 0; ix < theCount; ix++) { const ReSeqArray::Sequence* seq = getInfo(ix); Tag currentTag; size_t currentLength = getLengthAndTag(seq, currentTag); - if (currentLength == length){ + if (currentLength == length) { const Byte* ptr = reinterpret_cast(m_content.str() - + seq->m_index); - int comparison = m_ignoreCase ? _memicmp(ptr, toFind, length) - : _memcmp(ptr, toFind, length); - if (comparison == 0){ + + seq->m_index); + int comparison = + m_ignoreCase ? + _memicmp(ptr, toFind, length) : + _memcmp(ptr, toFind, length); + if (comparison == 0) { rc = ix; if (tag != NULL) *tag = currentTag; @@ -300,11 +301,12 @@ ReSeqArray::Index ReSeqArray::find(const Byte* toFind, size_t length, * @param true: The index is ok, the sequence is in the output buffer. * false: No copy has been done. */ -bool ReSeqArray::get(Index index, ReByteBuffer& value, Tag* tag) const{ +bool ReSeqArray::get(Index index, ReByteBuffer& value, Tag* tag) const { bool rc = false; - if (index < count()){ + if (index < count()) { const Sequence* seq = getInfo(index); - size_t length = tag == NULL ? getLength(seq) : getLengthAndTag(seq, *tag); + size_t length = + tag == NULL ? getLength(seq) : getLengthAndTag(seq, *tag); value.set(m_content.str() + seq->m_index, length); rc = true; } @@ -314,13 +316,14 @@ bool ReSeqArray::get(Index index, ReByteBuffer& value, Tag* tag) const{ * * @return the length of the element described in the Sequence seq */ -size_t ReSeqArray::getLength(const Sequence* seq) const{ +size_t ReSeqArray::getLength(const Sequence* seq) const { size_t rc; if (m_commonSize != INDIVIDUAL_SIZE) rc = m_commonSize; else { - const uint8_t* ptr = reinterpret_cast(seq) + m_offsetOfLength; - switch (m_sizeOfLength){ + const uint8_t* ptr = reinterpret_cast(seq) + + m_offsetOfLength; + switch (m_sizeOfLength) { case 1: rc = *ptr; break; @@ -335,7 +338,7 @@ size_t ReSeqArray::getLength(const Sequence* seq) const{ break; case 5: rc = ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24) - + ((int64_t)ptr[4] << 32); + + ((int64_t) ptr[4] << 32); break; default: assert(false); @@ -350,13 +353,14 @@ size_t ReSeqArray::getLength(const Sequence* seq) const{ * @param tag OUT: the tag of the element. * @return the byte sequence length of the element */ -size_t ReSeqArray::getLengthAndTag(const Sequence* seq, Tag& tag) const{ +size_t ReSeqArray::getLengthAndTag(const Sequence* seq, Tag& tag) const { size_t rc; if (m_commonSize != INDIVIDUAL_SIZE) rc = m_commonSize; else { - const uint8_t* ptr = reinterpret_cast(seq) + m_offsetOfLength; - switch (m_sizeOfLength){ + const uint8_t* ptr = reinterpret_cast(seq) + + m_offsetOfLength; + switch (m_sizeOfLength) { case 1: rc = *ptr; break; @@ -371,7 +375,7 @@ size_t ReSeqArray::getLengthAndTag(const Sequence* seq, Tag& tag) const{ break; case 5: rc = ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24) - | ((uint64_t)ptr[4] << 32); + | ((uint64_t) ptr[4] << 32); break; default: assert(false); @@ -380,7 +384,7 @@ size_t ReSeqArray::getLengthAndTag(const Sequence* seq, Tag& tag) const{ } } const uint8_t* ptr = reinterpret_cast(seq) + m_offsetOfTag; - switch (m_sizeOfTag){ + switch (m_sizeOfTag) { case 0: tag = 0; break; @@ -397,13 +401,15 @@ size_t ReSeqArray::getLengthAndTag(const Sequence* seq, Tag& tag) const{ tag = ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24); break; case 5: - tag = Tag(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (uint64_t(ptr[3]) << 24) - | (uint64_t(ptr[4]) << 32)); + tag = Tag( + ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (uint64_t(ptr[3]) << 24) + | (uint64_t(ptr[4]) << 32)); break; case 8: - tag = Tag(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (uint64_t(ptr[3]) << 24) - | (uint64_t(ptr[4]) << 32) | (uint64_t(ptr[5]) << 40) - | (uint64_t(ptr[6]) << 48) | (uint64_t(ptr[7]) << 56)); + tag = Tag( + ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (uint64_t(ptr[3]) << 24) + | (uint64_t(ptr[4]) << 32) | (uint64_t(ptr[5]) << 40) + | (uint64_t(ptr[6]) << 48) | (uint64_t(ptr[7]) << 56)); break; default: assert(false); @@ -417,13 +423,13 @@ size_t ReSeqArray::getLengthAndTag(const Sequence* seq, Tag& tag) const{ * * @param index The index of the entry to remove. */ -void ReSeqArray::remove(Index index){ - if (index <= count()){ +void ReSeqArray::remove(Index index) { + if (index <= count()) { m_age++; Sequence* seq = getInfo(index); size_t currentLength = getLength(seq); // Is this the last entry in m_content? - if (seq->m_index + currentLength >= m_content.length()){ + if (seq->m_index + currentLength >= m_content.length()) { // We can free the content: m_content.setLength(seq->m_index); } else { @@ -440,8 +446,8 @@ void ReSeqArray::remove(Index index){ * @param sourceLength The length of the new value. * @param tag An additional info associated to the source. */ -void ReSeqArray::set(Index index, const Byte* source, - size_t sourceLength, Tag tag){ +void ReSeqArray::set(Index index, const Byte* source, size_t sourceLength, + Tag tag) { if (index >= count()) add(index, source, sourceLength, tag); else { @@ -451,7 +457,7 @@ void ReSeqArray::set(Index index, const Byte* source, Sequence* seq = getInfo(index); size_t currentLength = getLength(seq); size_t indexContent; - if (currentLength >= sourceLength){ + if (currentLength >= sourceLength) { // Use the existing space: indexContent = seq->m_index; memcpy(m_content.buffer() + indexContent, source, sourceLength); @@ -462,15 +468,15 @@ void ReSeqArray::set(Index index, const Byte* source, indexContent = m_content.length(); m_content.append(source, sourceLength); } -/* printf("vor:\n%s\n", ReByteBuffer("") - .appendHexDump(m_list.str(), m_entrySize*(1+index), 0, - m_entrySize*2, "%4d: ", false, m_entrySize, m_entrySize).str()); - */ + /* printf("vor:\n%s\n", ReByteBuffer("") + .appendHexDump(m_list.str(), m_entrySize*(1+index), 0, + m_entrySize*2, "%4d: ", false, m_entrySize, m_entrySize).str()); + */ setSequence(seq, indexContent, sourceLength, tag); /*printf("dann:\n%s\n", ReByteBuffer("") - .appendHexDump(m_list.str(), m_entrySize*(1+index), 0, - m_entrySize*2, "%4d: ", false, m_entrySize, m_entrySize).str()); - */ + .appendHexDump(m_list.str(), m_entrySize*(1+index), 0, + m_entrySize*2, "%4d: ", false, m_entrySize, m_entrySize).str()); + */ } } @@ -485,14 +491,14 @@ void ReSeqArray::set(Index index, const Byte* source, * < 0: the current number of entries will be doubled * until - maxStringSpace is reached */ -void ReSeqArray::setCapacity(int maxEntries, int maxStringSpace){ - if (maxEntries != 0){ +void ReSeqArray::setCapacity(int maxEntries, int maxStringSpace) { + if (maxEntries != 0) { if (maxEntries > 0) m_list.ensureSize(maxEntries * m_entrySize); else m_list.setDelta(maxEntries * m_entrySize); } - if (maxStringSpace != 0){ + if (maxStringSpace != 0) { if (maxStringSpace > 0) m_content.ensureSize(maxStringSpace); else @@ -507,28 +513,29 @@ void ReSeqArray::setCapacity(int maxEntries, int maxStringSpace){ * @param length the length of the content * @param tag the tag of the element */ -void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag){ +void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, + Tag tag) { seq->m_index = index; - if (m_commonSize == INDIVIDUAL_SIZE){ + if (m_commonSize == INDIVIDUAL_SIZE) { uint8_t* ptr = reinterpret_cast(seq) + m_offsetOfLength; - switch (m_sizeOfLength){ + switch (m_sizeOfLength) { case 1: if (length > 0xff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_1, - i18n("length > 255: $1")).arg((int64_t) length).end(); + i18n("length > 255: $1")).arg((int64_t) length).end(); ptr[0] = length & 0xff; break; case 2: if (length > 0xffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_2, - i18n("length > 64k: $1")).arg((int64_t) length).end(); + i18n("length > 64k: $1")).arg((int64_t) length).end(); ptr[0] = length & 0xff; ptr[1] = (length >> 8) & 0xff; break; case 3: if (length > 0xffffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_3, - i18n("length > 16M: $1")).arg((int64_t) length).end(); + i18n("length > 16M: $1")).arg((int64_t) length).end(); ptr[0] = length & 0xff; ptr[1] = (length >> 8) & 0xff; ptr[2] = (length >> 16) & 0xff; @@ -536,7 +543,7 @@ void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag) case 4: if (length > 0xffffffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_4, - i18n("length > 4G: $1")).arg((int64_t) length).end(); + i18n("length > 4G: $1")).arg((int64_t) length).end(); ptr[0] = length & 0xff; ptr[1] = (length >> 8) & 0xff; ptr[2] = (length >> 16) & 0xff; @@ -545,7 +552,7 @@ void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag) case 5: if (length > 0xffffffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_5, - i18n("length > 1T: $1")).arg((int64_t) length).end(); + i18n("length > 1T: $1")).arg((int64_t) length).end(); ptr[0] = length & 0xff; ptr[1] = (length >> 8) & 0xff; ptr[2] = (length >> 16) & 0xff; @@ -557,26 +564,26 @@ void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag) break; } } - if (m_sizeOfTag > 0){ + if (m_sizeOfTag > 0) { uint8_t* ptr = reinterpret_cast(seq) + m_offsetOfTag; - switch (m_sizeOfTag){ + switch (m_sizeOfTag) { case 1: if (tag > 0xff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_6, - i18n("tag > 255: $1")).arg((int64_t) tag).end(); + i18n("tag > 255: $1")).arg((int64_t) tag).end(); ptr[0] = tag & 0xff; break; case 2: if (tag > 0xffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_7, - i18n("tag > 64k: $1")).arg((int64_t) tag).end(); + i18n("tag > 64k: $1")).arg((int64_t) tag).end(); ptr[0] = tag & 0xff; ptr[1] = (tag >> 8) & 0xff; break; case 3: if (tag > 0xffffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_8, - i18n("tag > 16M: $1")).arg((int64_t) tag).end(); + i18n("tag > 16M: $1")).arg((int64_t) tag).end(); ptr[0] = tag & 0xff; ptr[1] = (tag >> 8) & 0xff; ptr[2] = (tag >> 16) & 0xff; @@ -584,7 +591,7 @@ void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag) case 4: if (tag > 0xffffffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_9, - i18n("tag > 4G: $1")).arg((int64_t) tag).end(); + i18n("tag > 4G: $1")).arg((int64_t) tag).end(); ptr[0] = tag & 0xff; ptr[1] = (tag >> 8) & 0xff; ptr[2] = (tag >> 16) & 0xff; @@ -593,7 +600,7 @@ void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag) case 5: if (tag > 0xffffffff) globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SEQ_10, - i18n("tag > 1T: $1")).arg((int64_t) tag).end(); + i18n("tag > 1T: $1")).arg((int64_t) tag).end(); ptr[0] = tag & 0xff; ptr[1] = (tag >> 8) & 0xff; ptr[2] = (tag >> 16) & 0xff; @@ -621,8 +628,8 @@ void ReSeqArray::setSequence(Sequence* seq, Index index, size_t length, Tag tag) * * @param onNotOff true: the comparison will be case insensitive */ -void ReSeqArray::setIgnoreCase(bool onNotOff){ - if (m_ignoreCase != onNotOff){ +void ReSeqArray::setIgnoreCase(bool onNotOff) { + if (m_ignoreCase != onNotOff) { m_ignoreCase = onNotOff; if (m_sorted) sort(); @@ -633,8 +640,8 @@ void ReSeqArray::setIgnoreCase(bool onNotOff){ * * @param onNotOff true: the list will be sorted */ -void ReSeqArray::setSorted(bool onNotOff){ - if (m_sorted != onNotOff){ +void ReSeqArray::setSorted(bool onNotOff) { + if (m_sorted != onNotOff) { m_sorted = onNotOff; if (m_sorted) sort(); @@ -654,8 +661,9 @@ void ReSeqArray::setSorted(bool onNotOff){ * indiviually stored.
* If > 0 sizeOfLengthmust be 0! */ -void ReSeqArray::setSizes(int sizeOfTag, int sizeOfLength, size_t constantSize){ - switch(m_sizeOfLength = sizeOfLength){ +void ReSeqArray::setSizes(int sizeOfTag, int sizeOfLength, + size_t constantSize) { + switch (m_sizeOfLength = sizeOfLength) { case 0: case 1: case 2: @@ -665,11 +673,12 @@ void ReSeqArray::setSizes(int sizeOfTag, int sizeOfLength, size_t constantSize){ break; default: globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SIZES_2, - i18n("Invalid length length: $1 (instead of 0,1,2,4,5)")).arg(sizeOfTag).end(); + i18n("Invalid length length: $1 (instead of 0,1,2,4,5)")).arg( + sizeOfTag).end(); m_sizeOfLength = 8; break; } - switch(m_sizeOfTag = sizeOfTag){ + switch (m_sizeOfTag = sizeOfTag) { case 0: case 1: case 2: @@ -679,16 +688,17 @@ void ReSeqArray::setSizes(int sizeOfTag, int sizeOfLength, size_t constantSize){ break; default: globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SIZES_1, - i18n("Invalid tag length: $1 (instead of 0,1,2,3,4,8)")).arg(sizeOfTag).end(); + i18n("Invalid tag length: $1 (instead of 0,1,2,3,4,8)")).arg( + sizeOfTag).end(); m_sizeOfTag = 8; break; } m_offsetOfLength = sizeof(Index); m_offsetOfTag = sizeof(Index) + m_sizeOfLength; - if (sizeOfLength > 0 && constantSize != INDIVIDUAL_SIZE){ + if (sizeOfLength > 0 && constantSize != INDIVIDUAL_SIZE) { globalLogger()->sayF(LOG_ERROR | CAT_LIB, LC_SET_SIZES_1, - i18n("collision of sizeOfLength $1 and constantSize $2")) - .arg(sizeOfLength).arg((int) constantSize).end(); + i18n("collision of sizeOfLength $1 and constantSize $2")).arg( + sizeOfLength).arg((int) constantSize).end(); constantSize = 0; } m_commonSize = constantSize; @@ -698,7 +708,7 @@ void ReSeqArray::setSizes(int sizeOfTag, int sizeOfLength, size_t constantSize){ /** @brief Sorts the list. * Note: the comparison is controlled by m_ignoreCase. */ -void ReSeqArray::sort(){ +void ReSeqArray::sort() { // Build the heap in array so that largest value is at the root: int theCount = (int) count(); m_age++; @@ -727,7 +737,7 @@ void ReSeqArray::sort(){ * @param prefix NULL or a prefix of the output * @return buffer.str() (for chaining) */ -const char* ReSeqArray::status(ReByteBuffer& buffer, const char* prefix) const{ +const char* ReSeqArray::status(ReByteBuffer& buffer, const char* prefix) const { if (prefix != NULL) buffer.append(prefix); buffer.append("age: ").appendInt(m_age).append("\n"); @@ -742,19 +752,18 @@ const char* ReSeqArray::status(ReByteBuffer& buffer, const char* prefix) const{ * @param start the lower bound of the interval to inspect * @param endEnd the upper bound of the interval to inspect */ -void ReSeqArray::shiftDown(int start, int end){ - int root = start; +void ReSeqArray::shiftDown(int start, int end) { + int root = start; Sequence seq; // while the root has at least one child: - while (root * 2 + 1 < end ) { + while (root * 2 + 1 < end) { // left child: int child = 2 * root + 1; if (child + 1 < end && compare(child, child + 1) < 0) - child++; - if (compare(root, child) >= 0) - break; - else - { + child++; + if (compare(root, child) >= 0) + break; + else { // swap [child] with [root] Byte* ptrRoot = m_list.buffer() + root * m_entrySize; Byte* ptrChild = m_list.buffer() + child * m_entrySize; @@ -762,7 +771,7 @@ void ReSeqArray::shiftDown(int start, int end){ memcpy(ptrRoot, ptrChild, m_entrySize); memcpy(ptrChild, &seq, m_entrySize); root = child; - } - } + } + } } diff --git a/base/ReSeqArray.hpp b/base/ReSeqArray.hpp index 4489de5..eeee484 100644 --- a/base/ReSeqArray.hpp +++ b/base/ReSeqArray.hpp @@ -27,20 +27,21 @@ public: typedef unsigned int Index; typedef int64_t Tag; typedef struct { - Index m_index; + Index m_index; uint64_t m_length; - Tag m_tag; + Tag m_tag; } Sequence; public: - ReSeqArray(int deltaList = -1024 * (int) sizeof(size_t), int deltaBuffer = - 1024*1024); + ReSeqArray(int deltaList = -1024 * (int) sizeof(size_t), + int deltaBuffer = -1024 * 1024); virtual ~ReSeqArray(); ReSeqArray(const ReSeqArray& source); - ReSeqArray& operator = (const ReSeqArray& source); + ReSeqArray& operator =(const ReSeqArray& source); public: Index add(Index index, const Byte* source, size_t sourceLength, - Tag tag = 0); - bool binarySearch(const Byte* toFind, int length, Index& index, - Tag* tag = NULL) const; + Tag tag = 0); + bool binarySearch(const Byte* toFind, int length, Index& index, Tag* tag = + NULL) const; void clear(); int compare(Index index1, Index index2); /** @brief Returns the count of defined entries in the list. @@ -68,7 +69,8 @@ public: void remove(Index index); void set(Index index, const Byte* source, size_t sourceLength, Tag tag); void setCapacity(int maxIndices, int maxStringSpace); - void setSizes(int sizeOfTag, int sizeOfLength, size_t constantLength = INDIVIDUAL_SIZE); + void setSizes(int sizeOfTag, int sizeOfLength, size_t constantLength = + INDIVIDUAL_SIZE); void setSorted(bool onNotOff); void setIgnoreCase(bool onNotOff); void sort(); diff --git a/base/ReStringList.cpp b/base/ReStringList.cpp index a8b7c6d..89271a3 100644 --- a/base/ReStringList.cpp +++ b/base/ReStringList.cpp @@ -15,9 +15,8 @@ * @param deltaBuffer buffer reservation will be incremented by this amount */ ReStringList::ReStringList(int deltaList, int deltaBuffer, int sizeOfTag, - int sizeOfLength, size_t constantLength) : - ReSeqArray(deltaList, deltaBuffer) -{ + int sizeOfLength, size_t constantLength) : + ReSeqArray(deltaList, deltaBuffer) { setSizes(sizeOfTag, sizeOfLength, constantLength); } @@ -32,7 +31,7 @@ ReStringList::~ReStringList() { * by the same index.This class knows nothing about this * @return the instance itself (for chaining) */ -ReStringList& ReStringList::append(const char* source, Tag tagOf){ +ReStringList& ReStringList::append(const char* source, Tag tagOf) { add(-1, source, strlen(source) + 1, tagOf); return *this; } @@ -42,7 +41,7 @@ ReStringList& ReStringList::append(const char* source, Tag tagOf){ * @param tag a number which will stored with the string. Not interpreted by the instance * @return the instance itself (for chaining) */ -ReStringList& ReStringList::append(const ReByteBuffer& source, Tag tag){ +ReStringList& ReStringList::append(const ReByteBuffer& source, Tag tag) { int ix = add(-1, source.str(), source.length() + 1, tag); return *this; } @@ -52,7 +51,7 @@ ReStringList& ReStringList::append(const ReByteBuffer& source, Tag tag){ * @param source the new stringlist * @return the instance itself (for chaining) */ -ReStringList& ReStringList::append(const ReStringList& source){ +ReStringList& ReStringList::append(const ReStringList& source) { for (size_t ii = 0; ii < source.count(); ii++) add(-1, source.strOf(ii), source.sizeOf(ii), source.tagOf(ii)); return *this; @@ -68,7 +67,7 @@ ReStringList& ReStringList::append(const ReStringList& source){ * * @return true: the other instance is equal. false: Otherwise */ -bool ReStringList::equal(const ReStringList& toCompare) const{ +bool ReStringList::equal(const ReStringList& toCompare) const { bool rc = count() == toCompare.count() && firstDiff(toCompare) == -1; return rc; } @@ -82,14 +81,14 @@ bool ReStringList::equal(const ReStringList& toCompare) const{ * @return -1: the instances are equal. Otherwise: the index of the first different string * */ -int ReStringList::firstDiff(const ReStringList& toCompare) const{ +int ReStringList::firstDiff(const ReStringList& toCompare) const { int rc = -1; int count1 = count(); int count2 = toCompare.count(); int maxIx = count1 > count2 ? count2 : count1; - for (size_t ix = 0; rc == -1 && (int) ix < maxIx; ix++){ + for (size_t ix = 0; rc == -1 && (int) ix < maxIx; ix++) { if (sizeOf(ix) != toCompare.sizeOf(ix) - || strcmp(strOf(ix), toCompare.strOf(ix)) != 0) + || strcmp(strOf(ix), toCompare.strOf(ix)) != 0) rc = (int) ix; } if (rc == -1 && count1 != count2) @@ -105,7 +104,7 @@ int ReStringList::firstDiff(const ReStringList& toCompare) const{ * @param tagOf an item which will stored with the string. It can be retrieved by the same index. * This class knows nothing about this */ -void ReStringList::insert(Index index, const char* source, Tag tagOf){ +void ReStringList::insert(Index index, const char* source, Tag tagOf) { add(index, source, strlen(source) + 1, tagOf); } /** @brief Replaces an element in the internal array: a string and a tagOf. @@ -114,7 +113,7 @@ void ReStringList::insert(Index index, const char* source, Tag tagOf){ * @param source the new string of the replaced element * @param tagOf the tagOf of the replace element */ -void ReStringList::replace(Index index, const char* source, Tag tagOf){ +void ReStringList::replace(Index index, const char* source, Tag tagOf) { set(index, source, strlen(source) + 1, tagOf); } /** @brief Replaces a string in the internal array. @@ -124,9 +123,9 @@ void ReStringList::replace(Index index, const char* source, Tag tagOf){ * @param index the element with this index will be replaced * @param source the new string of the replaced element */ -void ReStringList::replaceString(Index index, const char* source){ +void ReStringList::replaceString(Index index, const char* source) { Tag tag; - if (index < count()){ + if (index < count()) { Sequence* seq = getInfo(index); getLengthAndTag(seq, tag); set(index, source, -1, tag); @@ -139,7 +138,7 @@ void ReStringList::replaceString(Index index, const char* source){ * @param index the element with this index will be replaced * @param tag the new tag */ -void ReStringList::replaceTag(Index index, Tag tag){ +void ReStringList::replaceTag(Index index, Tag tag) { ReByteBuffer buffer; if (get(index, buffer)) set(index, buffer.str(), buffer.length(), tag); @@ -152,9 +151,9 @@ void ReStringList::replaceTag(Index index, Tag tag){ * @return NULL: the index is too large. * Otherwise: the wanted string */ -const char* ReStringList::strOf(Index index) const{ +const char* ReStringList::strOf(Index index) const { const char* rc = NULL; - if (index < count()){ + if (index < count()) { Sequence* seq = getInfo(index); rc = m_content.str() + seq->m_index; } @@ -169,10 +168,10 @@ const char* ReStringList::strOf(Index index) const{ * @return -1: the index is too large.
* Otherwise: the wanted tag */ -ReSeqArray::Tag ReStringList::tagOf(Index index) const{ +ReSeqArray::Tag ReStringList::tagOf(Index index) const { Tag rc = -1; ReByteBuffer buffer; - if (! get(index, buffer, &rc)){ + if (!get(index, buffer, &rc)) { rc = -1; } return rc; @@ -185,9 +184,9 @@ ReSeqArray::Tag ReStringList::tagOf(Index index) const{ * Otherwise: the length of the index-th sequence * (including the trailing '\0') */ -size_t ReStringList::sizeOf(Index index) const{ +size_t ReStringList::sizeOf(Index index) const { size_t rc = 0; - if (index < count()){ + if (index < count()) { Sequence* seq = getInfo(index); rc = getLength(seq); } @@ -201,7 +200,7 @@ size_t ReStringList::sizeOf(Index index) const{ * Otherwise: the length of the index-th sequence * (excluding the trailing '\0') */ -size_t ReStringList::strLengthOf(Index index) const{ +size_t ReStringList::strLengthOf(Index index) const { size_t rc = 0; ReByteBuffer buffer; if (get(index, buffer)) @@ -212,10 +211,10 @@ size_t ReStringList::strLengthOf(Index index) const{ * * @return the sum of all string lengths stored in the array (including trailing '\0') */ -size_t ReStringList::sumOfSizes() const{ +size_t ReStringList::sumOfSizes() const { size_t rc = 0; ReByteBuffer buffer; - for (int ii = count() - 1; ii >= 0; ii--){ + for (int ii = count() - 1; ii >= 0; ii--) { get(ii, buffer); rc += buffer.length(); } @@ -225,10 +224,10 @@ size_t ReStringList::sumOfSizes() const{ * * @return the sum of all string lengths stored in the array */ -size_t ReStringList::sumOfStrLengths() const{ +size_t ReStringList::sumOfStrLengths() const { size_t rc = 0; - for (int ii = count() - 1; ii >= 0; ii--){ + for (int ii = count() - 1; ii >= 0; ii--) { Sequence* seq = getInfo(ii); rc += rc = getLength(seq); } @@ -243,12 +242,12 @@ size_t ReStringList::sumOfStrLengths() const{ * * @return -1: the string was not found. Otherwise: the index of the string */ -ReSeqArray::Index ReStringList::indexOf(const char* toFind, - bool ignoreCase, Index start) const{ +ReSeqArray::Index ReStringList::indexOf(const char* toFind, bool ignoreCase, + Index start) const { Index rc = (Index) -1; Index theCount = count(); - for (; rc == (Index) -1 && start < theCount; start++){ + for (; rc == (Index) -1 && start < theCount; start++) { const char* item = strOf(start); int rc2; if (ignoreCase) @@ -270,12 +269,12 @@ ReSeqArray::Index ReStringList::indexOf(const char* toFind, * @return -1: the string was not found. Otherwise: the index of the string */ ReSeqArray::Index ReStringList::nextStartingWith(Index start, - const char* prefix, bool ignoreCase){ + const char* prefix, bool ignoreCase) { Index rc = (Index) -1; Index theCount = count(); size_t length = strlen(prefix); - for (; rc == (Index) -1 && start < theCount; start++){ + for (; rc == (Index) -1 && start < theCount; start++) { const char* item = strOf(start); int rc2; if (ignoreCase) @@ -295,13 +294,13 @@ ReSeqArray::Index ReStringList::nextStartingWith(Index start, * @param append false: the list will be cleared at the beginning.
* true: the new content is stored at the end */ -void ReStringList::split(const char* list, char separator, bool append){ - if (! append) +void ReStringList::split(const char* list, char separator, bool append) { + if (!append) clear(); const char* end = list == NULL ? NULL : strchr(list, separator); const char* end2; ReByteBuffer item; - while(end != NULL){ + while (end != NULL) { if (separator == '\n' && end != list && end[-1] == '\r') end2 = end - 1; else @@ -326,13 +325,13 @@ void ReStringList::split(const char* list, char separator, bool append){ * @return buffer (for chaining) */ ReByteBuffer& ReStringList::join(const char* separator, ReByteBuffer& result, - bool append) const{ + bool append) const { size_t theCount = count(); - if (! append) + if (!append) result.setLength(0); size_t lengthSep = strlen(separator); - for (size_t ix = 0; ix < theCount; ix++){ + for (size_t ix = 0; ix < theCount; ix++) { result.append(strOf(ix), sizeOf(ix) - 1); if (ix != theCount - 1 && separator != NULL) result.append(separator, lengthSep); @@ -348,13 +347,13 @@ ReByteBuffer& ReStringList::join(const char* separator, ReByteBuffer& result, * * @return true: the file could be opened. false: otherwise */ -bool ReStringList::writeToFile(const char* filename, - const char* separator, const char* mode, const char* endOfFile){ +bool ReStringList::writeToFile(const char* filename, const char* separator, + const char* mode, const char* endOfFile) { bool rc = false; FILE* fp = fopen(filename, mode); - if (fp){ + if (fp) { size_t aCount = count(); - for (size_t ix = 0; ix < aCount; ix++){ + for (size_t ix = 0; ix < aCount; ix++) { fputs(strOf(ix), fp); if (ix != aCount - 1 && separator != NULL) fputs(separator, fp); @@ -376,16 +375,17 @@ bool ReStringList::writeToFile(const char* filename, * * @return true: the file could be opened. false: otherwise */ -bool ReStringList::readFromFile(const char* filename, bool cutNewline){ +bool ReStringList::readFromFile(const char* filename, bool cutNewline) { FILE* fp = fopen(filename, "r"); bool rc = false; - if (fp != NULL){ + if (fp != NULL) { char line[8096]; char cc; - while(fgets(line, sizeof line, fp) != NULL){ + while (fgets(line, sizeof line, fp) != NULL) { size_t length = strlen(line); - if (cutNewline){ - while(length > 0 && ( (cc = line[length - 1]) == '\n' || cc == '\r')) + if (cutNewline) { + while (length > 0 + && ((cc = line[length - 1]) == '\n' || cc == '\r')) line[--length] = '\0'; } add(-1, line, length + 1); diff --git a/base/ReStringList.hpp b/base/ReStringList.hpp index fff0330..934d407 100644 --- a/base/ReStringList.hpp +++ b/base/ReStringList.hpp @@ -31,10 +31,11 @@ * listOut.writeToFile("abc.csv"); *
*/ -class ReStringList : public ReSeqArray { +class ReStringList: public ReSeqArray { public: - ReStringList(int deltaList = 1024, int deltaBuffer = 1024, int sizeOfTag = 4, - int sizeOfLength = 1, size_t constantLength = INDIVIDUAL_SIZE); + ReStringList(int deltaList = 1024, int deltaBuffer = 1024, + int sizeOfTag = 4, int sizeOfLength = 1, size_t constantLength = + INDIVIDUAL_SIZE); virtual ~ReStringList(); public: ReStringList& append(const char* source, Tag tag = 0); @@ -43,11 +44,12 @@ public: bool equal(const ReStringList& toCompare) const; int firstDiff(const ReStringList& toCompare) const; Index indexOf(const char* toFind, bool ignoreCase = false, - Index start = 0) const; + Index start = 0) const; void insert(Index index, const char* source, Tag tag = 0); - ReByteBuffer& join(const char* separator, ReByteBuffer& result, bool append = false) const; - Index nextStartingWith(Index index, const char* prefix, - bool ignoreCase = false); + ReByteBuffer& join(const char* separator, ReByteBuffer& result, + bool append = false) const; + Index nextStartingWith(Index index, const char* prefix, bool ignoreCase = + false); bool readFromFile(const char* filename, bool cutNewline = true); void replace(Index index, const char* source, Tag tag = 0); void replaceString(Index index, const char* source); @@ -60,7 +62,7 @@ public: size_t sumOfStrLengths() const; Tag tagOf(Index index) const; bool writeToFile(const char* filename, const char* separator = "\n", - const char* mode = "w", const char* endOfFile = "\n"); + const char* mode = "w", const char* endOfFile = "\n"); }; #endif /* RESTRINGLIST_H_ */ diff --git a/base/ReStringUtils.cpp b/base/ReStringUtils.cpp index ba09ce7..6e7802c 100644 --- a/base/ReStringUtils.cpp +++ b/base/ReStringUtils.cpp @@ -20,14 +20,14 @@ const char ReStringUtils::AUTO_SEPARATOR = '\0'; * be taken from the list itself (the first character). */ bool ReStringUtils::isInList(const char* phrase, const char* list, - bool ignoreCase, char separator){ + bool ignoreCase, char separator) { if (separator == AUTO_SEPARATOR) separator = *list++; const char* end = strchr(list, separator); int phraseLength = strlen(phrase); bool rc = false; - while(! rc && end != NULL){ - if (end - list == phraseLength){ + while (!rc && end != NULL) { + if (end - list == phraseLength) { if (ignoreCase) rc = strnicmp(list, phrase, phraseLength) == 0; else @@ -38,7 +38,7 @@ bool ReStringUtils::isInList(const char* phrase, const char* list, list = end + 1; end = strchr(list, separator); } - if (! rc){ + if (!rc) { if (ignoreCase) rc = strnicmp(list, phrase, end - list) == 0; else @@ -67,7 +67,8 @@ bool ReStringUtils::isInList(const char* phrase, const char* list, * @result fullpath. (for chaining). */ ReByteBuffer& ReStringUtils::joinPath(ReByteBuffer& fullpath, - ReByteBuffer* protocol, ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext){ + ReByteBuffer* protocol, ReByteBuffer* path, ReByteBuffer* name, + ReByteBuffer* ext) { fullpath.setLength(0); if (protocol != NULL) fullpath.append(*protocol); @@ -98,7 +99,7 @@ ReByteBuffer& ReStringUtils::joinPath(ReByteBuffer& fullpath, * @result fullpath. (for chaining). */ ReByteBuffer& ReStringUtils::joinPath(ReByteBuffer& fullpath, - const char* protocol, const char* path, const char* name, const char* ext){ + const char* protocol, const char* path, const char* name, const char* ext) { fullpath.setLength(0); if (protocol != NULL) fullpath.append(protocol, strlen(protocol)); @@ -111,7 +112,6 @@ ReByteBuffer& ReStringUtils::joinPath(ReByteBuffer& fullpath, return fullpath; } - /** * Returns the length of an integer in a given text. * @@ -120,17 +120,17 @@ ReByteBuffer& ReStringUtils::joinPath(ReByteBuffer& fullpath, * @param value OUT: the value of the integer. May be NULL * @return the number of digits at the start of the text */ -int ReStringUtils::lengthOfUnsigned(const char* text, int length, - unsigned int* value){ +int ReStringUtils::lengthOfUnsigned(const char* text, int length, + unsigned int* value) { int rc = 0; unsigned int val = 0; char cc; if (length < 0) // the '\0' is automatically a stopper, no need to call strlen() length = INT_MAX; - while(rc < length && isdigit(cc = *text++)){ + while (rc < length && isdigit(cc = *text++)) { rc++; - val = 10*val + cc - '0'; + val = 10 * val + cc - '0'; } if (value != NULL && rc != 0) *value = val; @@ -163,11 +163,12 @@ int ReStringUtils::lengthOfUnsigned(const char* text, int length, * @param name Out: The name part of the filename. May be NULL. * @param ext Out: The extension. May be NULL. */ -void ReStringUtils::splitPath(const char* fullname, - ReByteBuffer* protocol, ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext){ - const char currentSlash = strchr(fullname, '/') != NULL ? '/' : OS_SEPARATOR_CHAR; +void ReStringUtils::splitPath(const char* fullname, ReByteBuffer* protocol, + ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext) { + const char currentSlash = + strchr(fullname, '/') != NULL ? '/' : OS_SEPARATOR_CHAR; const char* start = strchr(fullname, ':'); - if (protocol != NULL){ + if (protocol != NULL) { protocol->setLength(0); if (start != NULL) protocol->append(fullname, start - fullname + 1); @@ -179,7 +180,7 @@ void ReStringUtils::splitPath(const char* fullname, const char* end = strrchr(start, currentSlash); - if (path != 0){ + if (path != 0) { path->setLength(0); if (end != NULL) path->append(start, end - start + 1); @@ -187,14 +188,14 @@ void ReStringUtils::splitPath(const char* fullname, if (end != NULL) start = end + 1; end = strrchr(start, '.'); - if (name != NULL){ + if (name != NULL) { name->setLength(0); if (end == NULL) name->append(start, strlen(start)); else name->append(start, end - start); } - if (ext != NULL){ + if (ext != NULL) { ext->setLength(0); if (end != NULL) ext->append(end, strlen(end)); @@ -208,9 +209,10 @@ void ReStringUtils::splitPath(const char* fullname, * * @return < 0: string1 < string2 0: string1 == string2 > 0: string1 > string2 */ -int ReStringUtils::strnicmp(const char* string1, const char* string2, size_t length){ +int ReStringUtils::strnicmp(const char* string1, const char* string2, + size_t length) { int rc = 0; - while(rc == 0 && length-- > 0){ + while (rc == 0 && length-- > 0) { char cc1 = *string1++; char cc2 = *string2++; if (toupper(cc1) != toupper(cc2)) diff --git a/base/ReStringUtils.hpp b/base/ReStringUtils.hpp index 2b29ff9..f6306b5 100644 --- a/base/ReStringUtils.hpp +++ b/base/ReStringUtils.hpp @@ -19,16 +19,18 @@ public: //@ If used in isInList() the first character of the list will be the separator. static const char AUTO_SEPARATOR; public: - static bool isInList(const char* phrase, const char* list, - bool ignoreCase = true, char separator = AUTO_SEPARATOR); - static ReByteBuffer& joinPath(ReByteBuffer& result, - ReByteBuffer* protocol, ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext); - static ReByteBuffer& joinPath(ReByteBuffer& result, - const char* protocol, const char* path, const char* name, const char* ext); - static int lengthOfUnsigned(const char* text, int length = -1, unsigned int* value = NULL); - static void splitPath(const char* fullname, - ReByteBuffer* protocol, ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext); - static int strnicmp(const char* string1, const char* string2, size_t length); + static bool isInList(const char* phrase, const char* list, bool ignoreCase = + true, char separator = AUTO_SEPARATOR); + static ReByteBuffer& joinPath(ReByteBuffer& result, ReByteBuffer* protocol, + ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext); + static ReByteBuffer& joinPath(ReByteBuffer& result, const char* protocol, + const char* path, const char* name, const char* ext); + static int lengthOfUnsigned(const char* text, int length = -1, + unsigned int* value = NULL); + static void splitPath(const char* fullname, ReByteBuffer* protocol, + ReByteBuffer* path, ReByteBuffer* name, ReByteBuffer* ext); + static int strnicmp(const char* string1, const char* string2, + size_t length); }; #endif /* RESTRINGUTILS_H_ */ diff --git a/base/ReTestUnit.cpp b/base/ReTestUnit.cpp index bc90647..542f558 100644 --- a/base/ReTestUnit.cpp +++ b/base/ReTestUnit.cpp @@ -16,13 +16,11 @@ ReByteBuffer ReTestUnit::m_tempDir; * @param sourceFile the file where contain the tests * this will be used for error messages */ -ReTestUnit::ReTestUnit(const char* name, const char* sourceFile) - : - m_errorCount(0), - m_name(name), - m_sourceFile(sourceFile), - m_buffer() -{ +ReTestUnit::ReTestUnit(const char* name, const char* sourceFile) : + m_errorCount(0), + m_name(name), + m_sourceFile(sourceFile), + m_buffer() { int ix = m_sourceFile.rindexOf(OS_SEPARATOR, 1); if (ix >= 0) m_sourceFile.remove(0, ix + 1); @@ -42,9 +40,8 @@ ReTestUnit::~ReTestUnit() { * if false an error messsage will be issued * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertTrue(bool condition, int lineNo) -{ - if (! condition){ +void ReTestUnit::assertTrue(bool condition, int lineNo) { + if (!condition) { logF(true, i18n("%s-%d: not true!"), m_sourceFile.str(), lineNo); } } @@ -54,9 +51,8 @@ void ReTestUnit::assertTrue(bool condition, int lineNo) * if true an error messsage will be issued * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertFalse(bool condition, int lineNo) -{ - if (condition){ +void ReTestUnit::assertFalse(bool condition, int lineNo) { + if (condition) { logF(true, i18n("%s-%d: not false!"), m_sourceFile.str(), lineNo); } } @@ -66,9 +62,10 @@ void ReTestUnit::assertFalse(bool condition, int lineNo) * if not null an error messsage will be issued * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertNull(void* pointer, int lineNo){ - if (pointer != NULL){ - logF(true, "%s-%d: is not null %llx", m_sourceFile.str(), lineNo, (int64_t) pointer); +void ReTestUnit::assertNull(void* pointer, int lineNo) { + if (pointer != NULL) { + logF(true, "%s-%d: is not null %llx", m_sourceFile.str(), lineNo, + (int64_t) pointer); } } /** @brief Checks a pointer expression. A null value will be logged. @@ -77,8 +74,8 @@ void ReTestUnit::assertNull(void* pointer, int lineNo){ * if null an error messsage will be issued * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertNotNull(void* pointer, int lineNo){ - if (pointer == NULL){ +void ReTestUnit::assertNotNull(void* pointer, int lineNo) { + if (pointer == NULL) { logF(true, i18n("%s-%d: is null"), m_sourceFile.str(), lineNo); } } @@ -88,10 +85,10 @@ void ReTestUnit::assertNotNull(void* pointer, int lineNo){ * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqual(int expected, int current, int lineNo){ - if (expected != current){ +void ReTestUnit::assertEqual(int expected, int current, int lineNo) { + if (expected != current) { logF(true, i18n("%s-%d: expected: %ld (%lx) current: %ld (%lx)"), - m_sourceFile.str(), lineNo, expected, expected, current, current); + m_sourceFile.str(), lineNo, expected, expected, current, current); } } /** @brief Compares two integer values. If not equal this will be logged. @@ -100,10 +97,10 @@ void ReTestUnit::assertEqual(int expected, int current, int lineNo){ * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqual(int64_t expected, int64_t current, int lineNo){ - if (expected != current){ +void ReTestUnit::assertEqual(int64_t expected, int64_t current, int lineNo) { + if (expected != current) { logF(true, i18n("%s-%d: expected: %lld (%llx) current: %lld (%llx)"), - m_sourceFile.str(), lineNo, expected, expected, current, current); + m_sourceFile.str(), lineNo, expected, expected, current, current); } } /** @brief Compares two integer values. If not equal this will be logged. @@ -112,10 +109,11 @@ void ReTestUnit::assertEqual(int64_t expected, int64_t current, int lineNo){ * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqual(unsigned int expected, unsigned int current, int lineNo){ - if (expected != current){ +void ReTestUnit::assertEqual(unsigned int expected, unsigned int current, + int lineNo) { + if (expected != current) { logF(true, i18n("%s-%d: expected: %ld (%lx) current: %ld (%lx)"), - m_sourceFile.str(), lineNo, expected, expected, current, current); + m_sourceFile.str(), lineNo, expected, expected, current, current); } } /** @brief Compares two string values. If not equal this will be logged. @@ -124,13 +122,16 @@ void ReTestUnit::assertEqual(unsigned int expected, unsigned int current, int li * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqual(const char* expected, const char* current, int lineNo){ +void ReTestUnit::assertEqual(const char* expected, const char* current, + int lineNo) { if (expected == NULL) expected = ""; - if (current == NULL || strcmp(expected, current) != 0){ - logF(true, i18n("%s-%d: expected / current: length: %d / %d\n%.512s\n%.512s"), - m_sourceFile.str(), lineNo, strlen(expected), current == NULL ? 0 : strlen(current), - expected, current == NULL ? "" : current); + if (current == NULL || strcmp(expected, current) != 0) { + logF(true, + i18n("%s-%d: expected / current: length: %d / %d\n%.512s\n%.512s"), + m_sourceFile.str(), lineNo, strlen(expected), + current == NULL ? 0 : strlen(current), expected, + current == NULL ? "" : current); } } /** @brief Compares a string and a ReByteBuffer. If not equal this will be logged. @@ -139,7 +140,8 @@ void ReTestUnit::assertEqual(const char* expected, const char* current, int line * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqual(const char* expected, const ReByteBuffer& current, int lineNo){ +void ReTestUnit::assertEqual(const char* expected, const ReByteBuffer& current, + int lineNo) { assertEqual(expected, current.str(), lineNo); } /** @brief Compares two ReByteBuffer objects. If not equal this will be logged. @@ -148,7 +150,8 @@ void ReTestUnit::assertEqual(const char* expected, const ReByteBuffer& current, * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqual(const ReByteBuffer& expected, const ReByteBuffer& current, int lineNo){ +void ReTestUnit::assertEqual(const ReByteBuffer& expected, + const ReByteBuffer& current, int lineNo) { assertEqual(expected.str(), current.str(), lineNo); } /** @brief Compares two string values. If not equal this will be logged. @@ -157,11 +160,14 @@ void ReTestUnit::assertEqual(const ReByteBuffer& expected, const ReByteBuffer& c * @param current the current value * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqualIgnoreCase(const char* expected, const char* current, int lineNo){ - if (current == NULL || _stricmp(expected, current) != 0){ - logF(true, i18n("%s-%d: expected / current: length: %d / %d\n%.512s\n%.512s"), - m_sourceFile.str(), lineNo, strlen(expected), current == NULL ? 0 : strlen(current), - expected, current == NULL ? "" : current); +void ReTestUnit::assertEqualIgnoreCase(const char* expected, + const char* current, int lineNo) { + if (current == NULL || _stricmp(expected, current) != 0) { + logF(true, + i18n("%s-%d: expected / current: length: %d / %d\n%.512s\n%.512s"), + m_sourceFile.str(), lineNo, strlen(expected), + current == NULL ? 0 : strlen(current), expected, + current == NULL ? "" : current); } } @@ -170,14 +176,14 @@ void ReTestUnit::assertEqualIgnoreCase(const char* expected, const char* current * @param name the filename * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertFileExists(const char* name, int lineNo){ +void ReTestUnit::assertFileExists(const char* name, int lineNo) { struct stat info; - if (stat(name, &info) != 0){ - logF(true, i18n("%s-%d: File does not exist: %s"), - m_sourceFile.str(), lineNo, name); - } else if (S_ISDIR(info.st_mode)){ + if (stat(name, &info) != 0) { + logF(true, i18n("%s-%d: File does not exist: %s"), m_sourceFile.str(), + lineNo, name); + } else if (S_ISDIR(info.st_mode)) { logF(true, i18n("%s-%d: File does exist but this is a directory: %s"), - m_sourceFile.str(), lineNo, name); + m_sourceFile.str(), lineNo, name); } } /** @brief Checks whether two files have the same content. If not this will be logged. @@ -186,21 +192,22 @@ void ReTestUnit::assertFileExists(const char* name, int lineNo){ * @param name2 name of the 2nd file * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertEqualFiles(const char* name1, const char* name2, int lineNo){ +void ReTestUnit::assertEqualFiles(const char* name1, const char* name2, + int lineNo) { ReByteBuffer buffer; ReStringList list1; ReStringList list2; list1.readFromFile(name1); list2.readFromFile(name2); int ix = list1.firstDiff(list2); - if (ix >= 0){ + if (ix >= 0) { ReByteBuffer line1(list1.strOf(ix), list1.strLengthOf(ix)); - int ixLine = line1.firstDifference(list2.strOf(ix), list2.strLengthOf(ix)); + int ixLine = line1.firstDifference(list2.strOf(ix), + list2.strLengthOf(ix)); logF(true, i18n("%s-%d: Files differ in line %d-%d\n%s\n%s\n%s"), - m_sourceFile.str(), lineNo, ix + 1, ixLine, - (int) list1.count() > ix ? list1.strOf(ix) : "", - (int) list2.count() > ix ? list2.strOf(ix) : "", - colMarker(ixLine)); + m_sourceFile.str(), lineNo, ix + 1, ixLine, + (int) list1.count() > ix ? list1.strOf(ix) : "", + (int) list2.count() > ix ? list2.strOf(ix) : "", colMarker(ixLine)); } } @@ -211,7 +218,7 @@ void ReTestUnit::assertEqualFiles(const char* name1, const char* name2, int line * @param buffer OUT: the filename will be constructed in this buffer * @return buffer.str(): the full filename */ -const char* ReTestUnit::buildFilename(const char* node, ReByteBuffer& buffer){ +const char* ReTestUnit::buildFilename(const char* node, ReByteBuffer& buffer) { createTestDir(); buffer.setLength(0).append(m_tempDir).append(node); return buffer.str(); @@ -223,7 +230,7 @@ const char* ReTestUnit::buildFilename(const char* node, ReByteBuffer& buffer){ * @param col the column to mark. 0: the first column ... * @return a line marking the given column, e.g. "---^" */ -const char* ReTestUnit::colMarker(int col){ +const char* ReTestUnit::colMarker(int col) { if (col > 0) m_buffer.fill('-', 0, col - 1); else @@ -235,11 +242,11 @@ const char* ReTestUnit::colMarker(int col){ /** @brief Creates an empty temporary directory. * the name can be retrieved by getTestDir(). */ -void ReTestUnit::createTestDir(){ - if (m_tempDir.length() == 0){ - if (getenv("TMP") != NULL){ +void ReTestUnit::createTestDir() { + if (m_tempDir.length() == 0) { + if (getenv("TMP") != NULL) { m_tempDir = getenv("TMP"); - } else if (getenv("TEMP")){ + } else if (getenv("TEMP")) { m_tempDir = getenv("TEMP"); } else { m_tempDir = "/tmp/"; @@ -249,7 +256,7 @@ void ReTestUnit::createTestDir(){ struct stat info; int error = 0; if (lstat(m_tempDir.str(), &info) != 0) - if (_mkdir(m_tempDir.str(), ALLPERMS) != 0){ + if (_mkdir(m_tempDir.str(), ALLPERMS) != 0) { error = getLastOSError(); } ReDirectory::deleteTree(m_tempDir.str(), false); @@ -267,7 +274,7 @@ void ReTestUnit::createTestDir(){ * * @return a time usable for for runtime measurement */ -int ReTestUnit::milliSecSince(int64_t start){ +int ReTestUnit::milliSecSince(int64_t start) { #if defined __linux__ || defined __WIN32__ int64_t diff = clock() - start; return int(diff * 1000 / CLOCKS_PER_SEC); @@ -286,15 +293,15 @@ int ReTestUnit::milliSecSince(int64_t start){ * * @return a time usable for for runtime measurement */ -int64_t ReTestUnit::timer(){ +int64_t ReTestUnit::timer() { #if defined __linux__ return clock(); #elif defined __WIN32__ - return clock(); + return clock(); #if 0 - FILETIME timeBuffer; - GetSystemTimeAsFileTime(&timeBuffer); - return (int64_t) (((uint64_t) timeBuffer.dwHighDateTime << 32) + timeBuffer.dwLowDateTime); + FILETIME timeBuffer; + GetSystemTimeAsFileTime(&timeBuffer); + return (int64_t) (((uint64_t) timeBuffer.dwHighDateTime << 32) + timeBuffer.dwLowDateTime); #endif #else # error "timer not defined" @@ -305,7 +312,7 @@ int64_t ReTestUnit::timer(){ * * @return the name of a temporary directory */ -const char* ReTestUnit::testDir(){ +const char* ReTestUnit::testDir() { createTestDir(); return m_tempDir.str(); } @@ -315,12 +322,12 @@ const char* ReTestUnit::testDir(){ * @param filename the name of the file * @param content the content of the file. If NULL the file will be empty */ -void ReTestUnit::createFile(const char* filename, const char* content){ +void ReTestUnit::createFile(const char* filename, const char* content) { FILE* fp = fopen(filename, "w"); - if (fp == NULL){ + if (fp == NULL) { int error = getLastOSError(); logF(true, "createFile(%d): %s", error, filename); - } else if (content != NULL){ + } else if (content != NULL) { fwrite(content, strlen(content), 1, fp); fclose(fp); } @@ -330,24 +337,23 @@ void ReTestUnit::createFile(const char* filename, const char* content){ * @param filename the name of the file * @param content the content of the file. If NULL the file will be empty */ -void ReTestUnit::createDir(const char* filename){ +void ReTestUnit::createDir(const char* filename) { _mkdir(filename, ALLPERMS); } - /** @brief Checks whether a directory exists. If not this will be logged. * * @param dir the name of the directory * @param lineNo the line number of the test (for the error message) */ -void ReTestUnit::assertDirExists(const char* dir, int lineNo){ +void ReTestUnit::assertDirExists(const char* dir, int lineNo) { struct stat info; - if (stat(dir, &info) != 0){ + if (stat(dir, &info) != 0) { logF(true, i18n("%s-%d: Directory does not exist: %s"), - m_sourceFile.str(), lineNo, dir); - } else if (! S_ISDIR(info.st_mode)){ + m_sourceFile.str(), lineNo, dir); + } else if (!S_ISDIR(info.st_mode)) { logF(true, i18n("%s-%d: File exists but this is not a directory: %s"), - m_sourceFile.str(), lineNo, dir); + m_sourceFile.str(), lineNo, dir); } } @@ -360,11 +366,11 @@ void ReTestUnit::assertDirExists(const char* dir, int lineNo){ * * @return ! isError */ -bool ReTestUnit::log(bool isError, const char* message){ +bool ReTestUnit::log(bool isError, const char* message) { printf("%s%s\n", isError ? "+++ " : "", message); - if (isError) - m_errorCount++; - return ! isError; + if (isError) + m_errorCount++; + return !isError; } /** @brief Logs a formated message with placeholders. * @@ -376,7 +382,7 @@ bool ReTestUnit::log(bool isError, const char* message){ * * @return ! isError */ -bool ReTestUnit::logF(bool isError, const char* format, ...){ +bool ReTestUnit::logF(bool isError, const char* format, ...) { char buffer[2048]; va_list args; diff --git a/base/ReTestUnit.hpp b/base/ReTestUnit.hpp index 568aebd..86a9e53 100644 --- a/base/ReTestUnit.hpp +++ b/base/ReTestUnit.hpp @@ -15,19 +15,22 @@ public: ReTestUnit(const char* name, const char* sourcefile); virtual ~ReTestUnit(); private: - // Not accessible, not implemented! + // Not accessible, not implemented! ReTestUnit(const ReTestUnit& source); - // Not accessible, not implemented! + // Not accessible, not implemented! ReTestUnit& operator =(const ReTestUnit& source); public: void assertDirExists(const char* dir, int lineNo); - void assertEqual(int64_t expected, int64_t current, int lineNo); + void assertEqual(int64_t expected, int64_t current, int lineNo); void assertEqual(int expected, int current, int lineNo); void assertEqual(unsigned int expected, unsigned int current, int lineNo); void assertEqual(const char* expected, const char* current, int lineNo); - void assertEqual(const char* expected, const ReByteBuffer& current, int lineNo); - void assertEqual(const ReByteBuffer& expected, const ReByteBuffer& current, int lineNo); - void assertEqualIgnoreCase(const char* expected, const char* current, int lineNo); + void assertEqual(const char* expected, const ReByteBuffer& current, + int lineNo); + void assertEqual(const ReByteBuffer& expected, const ReByteBuffer& current, + int lineNo); + void assertEqualIgnoreCase(const char* expected, const char* current, + int lineNo); void assertEqualFiles(const char* name1, const char* name2, int lineNo); void assertFileExists(const char* name, int lineNo); void assertFalse(bool conditon, int lineNo); diff --git a/base/ReVarArgs.cpp b/base/ReVarArgs.cpp index 4188be4..f616d5b 100644 --- a/base/ReVarArgs.cpp +++ b/base/ReVarArgs.cpp @@ -24,15 +24,13 @@ char const ReVarArgs::PLACE_HOLDER_MARK = '$'; typedef ReByteBuffer::Byte Byte; /** @brief Constructor. */ -ReVarArgs::ReVarArgs(void) - : - m_argNo(0), - m_format(), - m_argBuffer(), - // m_args - m_stringIsReady(false), - m_trigger(NULL) -{ +ReVarArgs::ReVarArgs(void) : + m_argNo(0), + m_format(), + m_argBuffer(), + // m_args + m_stringIsReady(false), + m_trigger(NULL) { } /** @brief Constructor. @@ -40,15 +38,13 @@ ReVarArgs::ReVarArgs(void) * @param format The format with the placeholders. * @throws ReFormatException() There are gaps in the numbers of the placeholders. */ -ReVarArgs::ReVarArgs(const char* format) - : - m_argNo(0), - m_format(), - m_argBuffer(), - // m_args - m_stringIsReady(false), - m_trigger(NULL) -{ +ReVarArgs::ReVarArgs(const char* format) : + m_argNo(0), + m_format(), + m_argBuffer(), + // m_args + m_stringIsReady(false), + m_trigger(NULL) { reset(format); } /** @brief Resets the instance. @@ -60,7 +56,7 @@ ReVarArgs::ReVarArgs(const char* format) * @result A reference for the instance itself. This allows chaining. * @throws ReFormatException() There are gaps in the numbers of the placeholders. */ -ReVarArgs& ReVarArgs::reset(const char* format){ +ReVarArgs& ReVarArgs::reset(const char* format) { m_argNo = 0; memset(m_args, 0, sizeof m_args); m_format.setLength(0); @@ -72,19 +68,19 @@ ReVarArgs& ReVarArgs::reset(const char* format){ m_maxArgNo = 0; int position = m_format.indexOf(PLACE_HOLDER_MARK); int argNo; - while (position >= 0){ + while (position >= 0) { Byte cc = m_format.at(position + 1); - if (cc == PLACE_HOLDER_MARK){ - // $$ found: replace with $: + if (cc == PLACE_HOLDER_MARK) { + // $$ found: replace with $: position++; - } else if (! isdigit(cc)){ - // $ found. No action. + } else if (!isdigit(cc)) { + // $ found. No action. position++; } else { int argNoLen = 2; argNo = m_format.at(position + 1) - '0'; cc = m_format.at(position + 2); - if (isdigit(cc)){ + if (isdigit(cc)) { argNoLen++; argNo = 10 * argNo + cc - '0'; } @@ -95,9 +91,9 @@ ReVarArgs& ReVarArgs::reset(const char* format){ } position = m_format.indexOf(PLACE_HOLDER_MARK, position); } - // Searching the first gap: + // Searching the first gap: for (int ii = 1; ii < m_maxArgNo; ii++) - if (m_args[ii] == 0){ + if (m_args[ii] == 0) { char msg[128]; _snprintf(msg, sizeof msg, i18n("missing $%d in format: "), ii); throw ReFormatException(msg, format); @@ -110,32 +106,32 @@ ReVarArgs& ReVarArgs::reset(const char* format){ * * @throws ReFormatException There are wrong placeholders. */ -void ReVarArgs::replacePlaceholder(){ +void ReVarArgs::replacePlaceholder() { int position = m_format.indexOf(PLACE_HOLDER_MARK); int found = 0; int argNo; - while (position >= 0){ + while (position >= 0) { Byte cc = m_format.at(position + 1); - if (cc == PLACE_HOLDER_MARK){ - // $$ found: replace with $: + if (cc == PLACE_HOLDER_MARK) { + // $$ found: replace with $: m_format.remove(position, 1); position++; - } else if (! isdigit(cc)){ - // $ found. No action. + } else if (!isdigit(cc)) { + // $ found. No action. position++; } else { found++; int argNoLen = 2; argNo = m_format.at(position + 1) - '0'; cc = m_format.at(position + 2); - if (isdigit(cc)){ + if (isdigit(cc)) { argNoLen++; argNo = 10 * argNo + cc - '0'; } - if (argNo > m_argNo){ + if (argNo > m_argNo) { throw ReFormatException(i18n("Too large argument number: "), - m_format.buffer() + position, - __FILE__, __LINE__); + m_format.buffer() + position, + __FILE__, __LINE__); } else { char* arg = m_argBuffer.buffer() + m_args[argNo]; size_t argLen = strlen(arg); @@ -147,7 +143,7 @@ void ReVarArgs::replacePlaceholder(){ } if (found < m_argNo) throw ReFormatException(i18n("Format contains to few placeholders"), - m_format.buffer(), __FILE__, __LINE__); + m_format.buffer(), __FILE__, __LINE__); } /** @brief Stores an argument. * @@ -156,12 +152,12 @@ void ReVarArgs::replacePlaceholder(){ * @param value The argument string. * @param length The length of value. */ -void ReVarArgs::store(const char* value, int length){ +void ReVarArgs::store(const char* value, int length) { if (length < 0) length = strlen(value); - // Store the first index of the argument in m_argBuffer. + // Store the first index of the argument in m_argBuffer. m_args[++m_argNo] = m_argBuffer.length(); - // Store the string with trailing '\0': + // Store the string with trailing '\0': m_argBuffer.append(value, length); m_argBuffer.appendChar('\0'); if (m_trigger != NULL) @@ -174,7 +170,7 @@ void ReVarArgs::store(const char* value, int length){ * * @return The instance itself. This is useful for chaining. */ -ReVarArgs& ReVarArgs::arg(int value, const char* format){ +ReVarArgs& ReVarArgs::arg(int value, const char* format) { char number[256]; _snprintf(number, sizeof number, format, value); store(number); @@ -188,7 +184,7 @@ ReVarArgs& ReVarArgs::arg(int value, const char* format){ * * @return The instance itself. This is useful for chaining. */ -ReVarArgs& ReVarArgs::arg(int64_t value, const char* format){ +ReVarArgs& ReVarArgs::arg(int64_t value, const char* format) { char number[256]; _snprintf(number, sizeof number, format, value); store(number); @@ -202,7 +198,7 @@ ReVarArgs& ReVarArgs::arg(int64_t value, const char* format){ * * @return The instance itself. This is useful for chaining. */ -ReVarArgs& ReVarArgs::arg(unsigned int value, const char* format){ +ReVarArgs& ReVarArgs::arg(unsigned int value, const char* format) { char number[256]; _snprintf(number, sizeof number, format, value); store(number); @@ -215,7 +211,7 @@ ReVarArgs& ReVarArgs::arg(unsigned int value, const char* format){ * * @return The instance itself. This is useful for chaining. */ -ReVarArgs& ReVarArgs::arg(uint64_t value, const char* format){ +ReVarArgs& ReVarArgs::arg(uint64_t value, const char* format) { char number[256]; _snprintf(number, sizeof number, format, value); store(number); @@ -232,13 +228,14 @@ ReVarArgs& ReVarArgs::arg(uint64_t value, const char* format){ * * @return The instance itself. This is useful for chaining. */ -ReVarArgs& ReVarArgs::arg(const char* value, int minWidth, int maxWidth, bool alignRight){ +ReVarArgs& ReVarArgs::arg(const char* value, int minWidth, int maxWidth, + bool alignRight) { int length = strlen(value); if (maxWidth <= 0 || length < maxWidth) maxWidth = length; if (minWidth > maxWidth) maxWidth = minWidth; - if (length >= minWidth){ + if (length >= minWidth) { store(value, maxWidth); } else { ReByteBuffer buffer; @@ -247,7 +244,7 @@ ReVarArgs& ReVarArgs::arg(const char* value, int minWidth, int maxWidth, bool al memcpy(buffer.buffer() + minWidth - length, value, length); else memcpy(buffer.buffer(), value, length); - store (buffer.buffer(), buffer.length()); + store(buffer.buffer(), buffer.length()); } return *this; } @@ -258,7 +255,7 @@ ReVarArgs& ReVarArgs::arg(const char* value, int minWidth, int maxWidth, bool al * * @return The instance itself. This is useful for chaining. */ -ReVarArgs& ReVarArgs::arg(double value, const char* format){ +ReVarArgs& ReVarArgs::arg(double value, const char* format) { char number[256]; _snprintf(number, sizeof number, format, value); store(number); @@ -272,12 +269,11 @@ ReVarArgs& ReVarArgs::arg(double value, const char* format){ * the replaced placeholders. * @throws ReFormatException() Too few arguments. */ -const char* ReVarArgs::asCString(){ +const char* ReVarArgs::asCString() { if (m_argNo != m_maxArgNo) - throw ReFormatException(i18n("To few arguments"), - m_format.buffer()); + throw ReFormatException(i18n("To few arguments"), m_format.buffer()); - if (! m_stringIsReady){ + if (!m_stringIsReady) { replacePlaceholder(); m_stringIsReady = true; } @@ -290,7 +286,7 @@ const char* ReVarArgs::asCString(){ * After storing an argument (calling arg() * trigger->newArg() will be called. */ -void ReVarArgs::registerTrigger(ReVarArgTrigger* trigger){ +void ReVarArgs::registerTrigger(ReVarArgTrigger* trigger) { m_trigger = trigger; } /** @brief Marks the end of a arg() chain. @@ -306,6 +302,6 @@ void ReVarArgs::registerTrigger(ReVarArgTrigger* trigger){ * // The logging is done in the method end(). *
*/ -void ReVarArgs::end(void){ +void ReVarArgs::end(void) { // Nothing to do in this base class } diff --git a/base/ReVarArgs.hpp b/base/ReVarArgs.hpp index b20cf3d..c662585 100644 --- a/base/ReVarArgs.hpp +++ b/base/ReVarArgs.hpp @@ -12,7 +12,7 @@ /** This class will be used as callback method for ReVarArgs. */ -class ReVarArgTrigger{ +class ReVarArgTrigger { public: /** @brief This method will be called when a new ReVarArg::log() call was done. * The call was done after the insertion of the argument into the internal structures. @@ -27,7 +27,7 @@ public: *

Another known system with this functionality is printf. * But the ReVarArgs is typesafe.

*/ -class ReVarArgs{ +class ReVarArgs { private: static int const STD_SPACE; static char const PLACE_HOLDER_MARK; @@ -46,26 +46,27 @@ public: ReVarArgs& arg(int64_t value, const char* format = "%lld"); ReVarArgs& arg(unsigned int arg, const char* format = "%u"); ReVarArgs& arg(uint64_t value, const char* format = "%llu"); - ReVarArgs& arg(const char* arg, int minWidth = 0, int maxWidth = 1024, bool alignRight = false); + ReVarArgs& arg(const char* arg, int minWidth = 0, int maxWidth = 1024, + bool alignRight = false); ReVarArgs& arg(double arg, const char* format = "%f"); const char* asCString(); virtual void end(void); void registerTrigger(ReVarArgTrigger* trigger); protected: - //@ The current argument number: 1..99 - int m_argNo; - //@ The maximum of all argument numbers in the format. - int m_maxArgNo; - //@ Stores the format. When the first call of asCharPtr() - //@ the expanded string will be stored here. - ReByteBuffer m_format; - //@ Stores the argument strings including the trailing '\0'. - ReByteBuffer m_argBuffer; - //@ Stores the positions (indexes) of the arguments in m_argBuffer. - int m_args[100]; - //@ true: The compound string is constructed (with expanded placeholders). false: Otherwise. - bool m_stringIsReady; - //@ Callback mechanism: m_trigger.newArg() will be called in store(). + //@ The current argument number: 1..99 + int m_argNo; + //@ The maximum of all argument numbers in the format. + int m_maxArgNo; + //@ Stores the format. When the first call of asCharPtr() + //@ the expanded string will be stored here. + ReByteBuffer m_format; + //@ Stores the argument strings including the trailing '\0'. + ReByteBuffer m_argBuffer; + //@ Stores the positions (indexes) of the arguments in m_argBuffer. + int m_args[100]; + //@ true: The compound string is constructed (with expanded placeholders). false: Otherwise. + bool m_stringIsReady; + //@ Callback mechanism: m_trigger.newArg() will be called in store(). ReVarArgTrigger* m_trigger; }; diff --git a/base/baselocations.hpp b/base/baselocations.hpp index a5e99e1..39f9eab 100644 --- a/base/baselocations.hpp +++ b/base/baselocations.hpp @@ -13,28 +13,28 @@ /** The files of the REal PUBlic LIB use the range from 50000 until 99999. */ enum RELOC_LIB { - LC_CONFIGFILE = 50000, - LC_DIRTOOLS = 50100, - LC_SEQARRAY = 50200, - LC_HASHLIST = 50300, - LC_TRAVERSER = 50400, + LC_CONFIGFILE = 50000, + LC_DIRTOOLS = 50100, + LC_SEQARRAY = 50200, + LC_HASHLIST = 50300, + LC_TRAVERSER = 50400, }; enum RELOC_UDPCONNECTION { - LC_UDPCONNECTION_CONSTRUCT = 50101, - LC_UDPCONNECTION_RECEIVE_1 = 50102, - LC_UDPCONNECTION_RECEIVE_2 = 50103, - LC_UDPCONNECTION_SEND_1 = 50104, - LC_UDPCONNECTION_SEND_2 = 50105, - LC_UDPCONNECTION_CLOSE_1 = 50106, - LC_UDPCONNECTION_CLOSE_2 = 50107, - LC_UDPCONNECTION_CONNECT_1 = 50108, - LC_UDPCONNECTION_CONNECT_2 = 50109, - LC_UDPCONNECTION_RUN_1 = 50110, + LC_UDPCONNECTION_CONSTRUCT = 50101, + LC_UDPCONNECTION_RECEIVE_1 = 50102, + LC_UDPCONNECTION_RECEIVE_2 = 50103, + LC_UDPCONNECTION_SEND_1 = 50104, + LC_UDPCONNECTION_SEND_2 = 50105, + LC_UDPCONNECTION_CLOSE_1 = 50106, + LC_UDPCONNECTION_CLOSE_2 = 50107, + LC_UDPCONNECTION_CONNECT_1 = 50108, + LC_UDPCONNECTION_CONNECT_2 = 50109, + LC_UDPCONNECTION_RUN_1 = 50110, }; enum RELOC_LOGGER { - LC_LOGGER_SAYF_OPEN = 50201, + LC_LOGGER_SAYF_OPEN = 50201, }; enum RELOC_CSTRING { - LC_CSTRING_REPLACE_1 = 50301, + LC_CSTRING_REPLACE_1 = 50301, }; #endif /* BASELOCATIONS_HPP_ */ diff --git a/base/rebase.hpp b/base/rebase.hpp index c368f92..f37379d 100644 --- a/base/rebase.hpp +++ b/base/rebase.hpp @@ -33,10 +33,10 @@ # include # include # include - typedef u_int64_t uint64_t; - typedef u_int8_t uint8_t; - typedef __off_t ReFileSize_t; - typedef timespec ReFileTime_t; +typedef u_int64_t uint64_t; +typedef u_int8_t uint8_t; +typedef __off_t ReFileSize_t; +typedef timespec ReFileTime_t; # define _strdup strdup # define _unlink unlink # define _strnicmp(s1, s2, n) strncasecmp(s1, s2, n) @@ -47,7 +47,7 @@ # define _rmdir(path) rmdir(path) # define OS_SEPARATOR_CHAR '/' # define OS_SEPARATOR "/" -inline int getLastOSError(){ +inline int getLastOSError() { return errno; } #elif defined __WIN32__ @@ -57,20 +57,20 @@ inline int getLastOSError(){ # define lstat stat # define OS_SEPARATOR_CHAR '\\' # define OS_SEPARATOR "\\" - typedef _int64 int64_t; - typedef unsigned long long uint64_t; - typedef unsigned char uint8_t; - typedef unsigned long uint32_t; - typedef long int int32_t; - typedef int64_t ReFileSize_t; - typedef FILETIME ReFileTime_t; +typedef _int64 int64_t; +typedef unsigned long long uint64_t; +typedef unsigned char uint8_t; +typedef unsigned long uint32_t; +typedef long int int32_t; +typedef int64_t ReFileSize_t; +typedef FILETIME ReFileTime_t; # define S_ISDIR(mode) (((mode) & _S_IFDIR) != 0) # define ALLPERMS 0 //# define _mkdir(name, mode) (!CreateDirectory(name, NULL)) # define _mkdir(name, mode) _mkdir(name) - inline int getLastOSError(){ - return GetLastError(); - } +inline int getLastOSError() { + return GetLastError(); +} #endif #define RE_TESTUNIT diff --git a/cunit/basetest.cpp b/cunit/basetest.cpp index 75d669e..9c8c397 100644 --- a/cunit/basetest.cpp +++ b/cunit/basetest.cpp @@ -9,8 +9,8 @@ #include "base/rebase.hpp" #if defined RE_TESTUNIT extern void testReBase(void); -void testReBase(void){ - try{ +void testReBase(void) { + try { extern void testReProgramArgs(void); testReProgramArgs(); extern void testReI18N(void); @@ -37,7 +37,7 @@ void testReBase(void){ testReLogger(); extern void testReDirectory(void); testReDirectory(); - } catch (ReException e){ + } catch (ReException e) { fprintf(stderr, "unexpected exception: %s\n", e.getMessage()); } } diff --git a/cunit/cuReByteBuffer.cpp b/cunit/cuReByteBuffer.cpp index c261103..c73393e 100644 --- a/cunit/cuReByteBuffer.cpp +++ b/cunit/cuReByteBuffer.cpp @@ -7,14 +7,15 @@ * The latest sources: https://github.com/republib */ #include "base/rebase.hpp" -class TestReByteBuffer : public ReTestUnit { +class TestReByteBuffer: public ReTestUnit { typedef ReByteBuffer::Byte Byte; public: - TestReByteBuffer() : ReTestUnit("ReByteBuffer", __FILE__){ + TestReByteBuffer() : + ReTestUnit("ReByteBuffer", __FILE__) { run(); } private: - void run(){ + void run() { testAppendFix(); testEnsureLastChar(); testLastChar(); @@ -46,7 +47,7 @@ private: testSplice(); testReplace(); } - void testAppendFix(){ + void testAppendFix() { ReByteBuffer buffer; // maxLength exceeded // odd maxlength: @@ -56,7 +57,8 @@ private: buffer.appendFix("abcdefg", -1, 4, 4, "."); checkEqu("12*56ab.g", buffer); // given separator with more than one char / no separator - buffer.appendFix("ABCDEF", -1, 5, 5, "...").appendFix("xyz", -1, 2, 0, NULL); + buffer.appendFix("ABCDEF", -1, 5, 5, "...").appendFix("xyz", -1, 2, 0, + NULL); checkEqu("12*56ab.gA...Fxz", buffer); buffer = "x"; @@ -81,7 +83,7 @@ private: checkEqu("y1234a", buffer); } - void testEnsureLastChar(){ + void testEnsureLastChar() { ReByteBuffer buffer("1/"); buffer.ensureLastChar('/'); checkEqu(2U, buffer.length()); @@ -90,13 +92,13 @@ private: checkEqu(3U, buffer.length()); checkEqu('x', buffer.lastChar()); } - void testLastChar(){ + void testLastChar() { ReByteBuffer buffer("12345"); checkEqu('5', buffer.lastChar()); buffer.setLength(0); checkEqu('\0', buffer.lastChar()); } - void testReduceLength(){ + void testReduceLength() { ReByteBuffer buffer("12345"); buffer.reduceLength(); checkEqu(4U, buffer.length()); @@ -110,13 +112,13 @@ private: buffer.reduceLength(99); checkEqu(0U, buffer.length()); } - void testRemoveLastChar(){ + void testRemoveLastChar() { ReByteBuffer buffer("123"); buffer.removeLastChar('x').removeLastChar('3'); checkEqu(2U, buffer.length()); checkEqu("12", buffer); } - void testAppendChar(){ + void testAppendChar() { ReByteBuffer buffer; buffer.appendChar('1'); checkEqu(1U, buffer.length()); @@ -142,7 +144,7 @@ private: checkEqu("12xyyy", buffer); } - void testAppendFloat(){ + void testAppendFloat() { ReByteBuffer buffer; buffer.append(125 / 100.0); @@ -150,7 +152,7 @@ private: buffer.append(0.333, "%.2f"); checkEqu("1.2500000.33", buffer); } - void testAppendInt64(){ + void testAppendInt64() { ReByteBuffer buffer; buffer.appendInt((int64_t) 12345678901ll); checkEqu("12345678901", buffer); @@ -158,63 +160,67 @@ private: checkEqu("12345678901123456789", buffer); } - void testEnsureSize2(){ + void testEnsureSize2() { ReByteBuffer buffer; buffer.setLength(PRIMARY_BUFFER_SIZE - 1); buffer.fill('x', PRIMARY_BUFFER_SIZE - 1); - checkEqu(PRIMARY_BUFFER_SIZE - 1, (int) buffer.capacity()); + checkEqu(PRIMARY_BUFFER_SIZE - 1, (int ) buffer.capacity()); buffer.ensureSize(PRIMARY_BUFFER_SIZE); - checkEqu(PRIMARY_BUFFER_SIZE*2 - 1, (int) buffer.capacity()); + checkEqu(PRIMARY_BUFFER_SIZE*2 - 1, (int ) buffer.capacity()); } - void testHexDump(){ + void testHexDump() { ReByteBuffer buf; /* appendHexDump(const char* data, size_t length, int offset = 0, int bytePerLine = 16, - const char* offsetFormat = "%04x ", bool withAscii = true, - int groupWidth = 1, int gapBehind = -1, const char* separator = " | "); - */ + const char* offsetFormat = "%04x ", bool withAscii = true, + int groupWidth = 1, int gapBehind = -1, const char* separator = " | "); + */ buf.appendHexDump("abcdefghijklmnopq"); - checkEqu("0000: 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 | abcdefgh ijklmnop\n" - "0010: 71 | q \n", - buf); + checkEqu( + "0000: 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 | abcdefgh ijklmnop\n" + "0010: 71 | q \n", + buf); buf.setLength(0).appendHexDump("abcdefghijklmnopq", 16); - checkEqu("0000: 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 | abcdefgh ijklmnop\n", - buf); - buf.setLength(0).appendHexDump("\t\nü23456789x123456", -1, 20, 8, "%3d: ", true, - 4, 0, NULL); + checkEqu( + "0000: 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 | abcdefgh ijklmnop\n", + buf); + buf.setLength(0).appendHexDump("\t\nü23456789x123456", -1, 20, 8, + "%3d: ", true, 4, 0, NULL); checkEqu(" 20: 090ac3bc 32333435....2345\n" " 28: 36373839 783132336789x123\n" " 36: 343536 456 \n", buf); - buf.setLength(0).appendHexDump("abcdefghijk", -1, 0, 8, "%3d: ", true, 2, 4); + buf.setLength(0).appendHexDump("abcdefghijk", -1, 0, 8, "%3d: ", true, + 2, 4); checkEqu(" 0: 6162 6364 6566 6768 | abcd efgh\n" - " 8: 696a 6b | ijk \n", buf); + " 8: 696a 6b | ijk \n", buf); } - void testFill(){ + void testFill() { ReByteBuffer buf; buf.fill('=', 0, 3); checkEqu("===", buf); buf.fill('x', 1, 2); checkEqu("=x=", buf); } - void testAppendMilliSec(){ + void testAppendMilliSec() { ReByteBuffer buf; checkEqu("5.123", buf.appendMilliSec(5123)); - checkEqu("32:45.789", buf.setLength(0) - .appendMilliSec(32*60*1000+45789)); - checkEqu("17:04:06.976", buf.setLength(0) - .appendMilliSec(17*3600*1000 + 4*60*1000 + 6976)); + checkEqu("32:45.789", + buf.setLength(0).appendMilliSec(32 * 60 * 1000 + 45789)); + checkEqu("17:04:06.976", + buf.setLength(0).appendMilliSec( + 17 * 3600 * 1000 + 4 * 60 * 1000 + 6976)); } - void testSetDelta(){ + void testSetDelta() { ReByteBuffer buf("abcd"); int maxDelta = 512 * (1 << 10); - buf.setDelta(- maxDelta); + buf.setDelta(-maxDelta); int count = 0; - while(buf.capacity() < (size_t) maxDelta){ + while (buf.capacity() < (size_t) maxDelta) { buf.ensureSize(buf.capacity() + 2); count++; } checkT(count <= 10 + 1); } - void testFirstDiff(){ + void testFirstDiff() { ReByteBuffer buf("abcd"); // firstDifference(const Byte* source, size_t length, int start, bool ignoreCase) // ignoreCase == false: @@ -263,14 +269,14 @@ private: checkEqu(0, buf.firstDifference("cdx", 1, -1, true)); checkEqu(0, buf.firstDifference("cdx", 1, -1, false)); } - void testCount(){ + void testCount() { ReByteBuffer buffer("aabbaabb"); checkEqu(4, buffer.count("a")); checkEqu(4, buffer.count("b")); checkEqu(2, buffer.count("ab")); checkEqu(1, buffer.count("aabbaabb")); } - void testStartsWidth(){ + void testStartsWidth() { // . . . . . . . . . 01234567 ReByteBuffer buffer("aabbaabb"); // case sensitive @@ -308,7 +314,7 @@ private: checkF(buffer.startsWith(buffer3.str(), 3, true)); } - void testEndsWidth(){ + void testEndsWidth() { // . . . . . . . . . 01234567 ReByteBuffer buffer("aabbaabb"); // case sensitive @@ -338,7 +344,7 @@ private: checkT(buffer.endsWith(buffer2.str(), 3, true)); } - void testIndexOf(){ + void testIndexOf() { // . . . . . . . . . 01234567 ReByteBuffer buffer("aabbaabb"); // const Byte* toFind, size_t toFindLength, int start,int end, bool ignoreCase @@ -358,7 +364,7 @@ private: checkEqu(-1, buffer.indexOf("Aa", 2, 1, 5, true)); checkEqu(1, buffer.indexOf("aB", 2, 0, -1, true)); } - void testRIndexOf(){ + void testRIndexOf() { // . . . . . . . . . 01234567 ReByteBuffer buffer("aabbaabb"); // const Byte* toFind, size_t toFindLength, int start,int end, bool ignoreCase @@ -380,14 +386,14 @@ private: checkEqu(1, buffer.rindexOf("Ab", 2, 1, 5, true)); checkEqu(4, buffer.rindexOf("Aa", 2, 0, -1, true)); } - void testBasic(){ + void testBasic() { ReByteBuffer buffer(10); - buffer.append((Byte*)"123", 3); + buffer.append((Byte*) "123", 3); checkEqu("123", buffer.buffer()); checkEqu("123", buffer); checkEqu(3u, buffer.length()); - buffer.append((Byte*)"ab", 2); + buffer.append((Byte*) "ab", 2); checkEqu("123ab", buffer.buffer()); checkEqu(5u, buffer.length()); @@ -401,7 +407,7 @@ private: buffer.setLengthAndFillOut(PRIMARY_BUFFER_SIZE - 1, 'y'); buffer.setLengthAndFillOut(PRIMARY_BUFFER_SIZE, 'z'); checkEqu("yyz", buffer.buffer() + PRIMARY_BUFFER_SIZE - 3); - checkEqu(PRIMARY_BUFFER_SIZE + 10 - 1, (int) buffer.capacity()); + checkEqu(PRIMARY_BUFFER_SIZE + 10 - 1, (int ) buffer.capacity()); ReByteBuffer buffer2; buffer2.set("xyz", -1); @@ -441,17 +447,17 @@ private: checkEqu("abc", buf3); checkEqu("abc", buf1); } - void testAt(){ + void testAt() { ReByteBuffer buf1; buf1.set("abc", 3); - for (size_t ii = 0; ii < buf1.length(); ii++){ - checkEqu(int('a' + ii), (int) buf1.at(ii)); + for (size_t ii = 0; ii < buf1.length(); ii++) { + checkEqu(int('a' + ii), (int ) buf1.at(ii)); } checkEqu(0, buf1.at(-1)); checkEqu(0, buf1.at(3)); checkEqu(0, buf1.at(4)); } - void testAtoi(){ + void testAtoi() { ReByteBuffer buffer; buffer.set("y1234", -1); @@ -476,7 +482,6 @@ private: buffer.set("187654302ab", -1); checkEqu(187654302, buffer.atoi()); - buffer.set("y0x1234", -1); checkEqu(0x1, buffer.atoi(1, 4)); @@ -496,16 +501,16 @@ private: checkEqu(0, buffer.atoi(5, 6)); buffer.set("0x98765432", -1); - checkEqu(0x98765432, (unsigned) buffer.atoi()); + checkEqu(0x98765432, (unsigned ) buffer.atoi()); buffer.set("0xabcdef01", -1); - checkEqu(0xabcdef01, (unsigned) buffer.atoi()); + checkEqu(0xabcdef01, (unsigned ) buffer.atoi()); buffer.set("0xABCDEF01", -1); - checkEqu(0xabcdef01, (unsigned) buffer.atoi()); + checkEqu(0xabcdef01, (unsigned ) buffer.atoi()); buffer.set("0xaFFe01", -1); - checkEqu(0xaFFe01u, (unsigned) buffer.atoi()); + checkEqu(0xaFFe01u, (unsigned ) buffer.atoi()); } - void testEnsureSizeGetLength(){ + void testEnsureSizeGetLength() { ReByteBuffer buf1; buf1.ensureSize(2000); checkEqu(2000u, buf1.capacity()); @@ -522,7 +527,7 @@ private: checkEqu(2000u, buf1.capacity()); } - void testIndexOfCharRIndexOfChar(){ + void testIndexOfCharRIndexOfChar() { ReByteBuffer buffer; buffer.set("123123", -1); checkEqu(0, buffer.indexOf('1')); @@ -559,7 +564,7 @@ private: checkEqu(-1, buffer.indexOf("234", -1, 0)); checkEqu(-1, buffer.indexOf("23", -1, 5)); } - void testInsert(){ + void testInsert() { ReByteBuffer buf1; checkT(buf1.insert(0, "123", 2)); checkEqu("12", buf1); @@ -581,7 +586,7 @@ private: checkF(buf1.insert(8, "/", 1)); } - void testRemove(){ + void testRemove() { ReByteBuffer buf1; buf1.set("1234567890", 10); checkT(buf1.remove(0, 2)); @@ -608,7 +613,7 @@ private: checkEqu("", buf1); checkEqu(0u, buf1.length()); } - void testReplace(){ + void testReplace() { ReByteBuffer buffer; buffer.set("1234", 4); @@ -622,7 +627,7 @@ private: buffer.replaceAll("$", 1, "XX", 2); checkEqu("XXXXxXXXX", buffer); } - void testSplice(){ + void testSplice() { ReByteBuffer buffer; buffer.append((Byte*) "12.ab", 5); @@ -654,7 +659,7 @@ private: }; extern void testReByteBuffer(void); -void testReByteBuffer(void){ +void testReByteBuffer(void) { TestReByteBuffer unit; } diff --git a/cunit/cuReCString.cpp b/cunit/cuReCString.cpp index 0f4bb08..737a43c 100644 --- a/cunit/cuReCString.cpp +++ b/cunit/cuReCString.cpp @@ -9,17 +9,18 @@ #include "base/rebase.hpp" #include "string/restring.hpp" -class TestCReString : public ReTestUnit { +class TestCReString: public ReTestUnit { public: - TestCReString() : ReTestUnit("ReCString", __FILE__){ + TestCReString() : + ReTestUnit("ReCString", __FILE__) { run(); } private: - void run(){ - testMemicmp(); + void run() { + testMemicmp(); testReplaceSubstring(); } - void testReplaceSubstring(){ + void testReplaceSubstring() { char buffer[256]; strcpy(buffer, "12.ab"); replaceSubstring(buffer, sizeof buffer, 0, "xy"); @@ -33,23 +34,23 @@ private: replaceSubstring(buffer, 6, 0, "x"); checkEqu("xw.ab", buffer); } - void testMemicmp(){ - checkEqu(0, _memicmp((void*) "abcd", (void*) "abcx", 3u)); + void testMemicmp() { + checkEqu(0, _memicmp((void* ) "abcd", (void* ) "abcx", 3u)); checkEqu(0, _memicmp("aBcd", "AbCx", 3)); - checkEqu(1, _memicmp("bbcd", "abcx", 3)); - checkEqu(-1, _memicmp("abcd", "bbcx", 3)); + checkEqu(1, _memicmp("bbcd", "abcx", 3)); + checkEqu(-1, _memicmp("abcd", "bbcx", 3)); - checkEqu(1, _memicmp("Bbcd", "abcx", 3)); - checkEqu(-1, _memicmp("aBcd", "bbcx", 3)); + checkEqu(1, _memicmp("Bbcd", "abcx", 3)); + checkEqu(-1, _memicmp("aBcd", "bbcx", 3)); - checkEqu(1, _memicmp("bbcd", "abcx", 3)); - checkEqu(-1, _memicmp("ABcd", "bbcx", 3)); - } + checkEqu(1, _memicmp("bbcd", "abcx", 3)); + checkEqu(-1, _memicmp("ABcd", "bbcx", 3)); + } }; extern void testReCString(void); -void testReCString(void){ +void testReCString(void) { TestCReString unit; } diff --git a/cunit/cuReDirTools.cpp b/cunit/cuReDirTools.cpp index b846d32..b7e089a 100644 --- a/cunit/cuReDirTools.cpp +++ b/cunit/cuReDirTools.cpp @@ -14,66 +14,66 @@ static const char* s_empty[] = { NULL }; // count of seconds from 1.1.1970 until 1.1.1980: const int tenYear = (365 * 10 + 2) * 24 * 3600; -class TestReDirTools : public ReTestUnit { +class TestReDirTools: public ReTestUnit { public: - TestReDirTools() : ReTestUnit("ReDirTools", __FILE__), - // m_base - // m_buffer - m_testAll(true), - m_logger(ReLogger::globalLogger()) - { - m_base = testDir(); + TestReDirTools() : + ReTestUnit("ReDirTools", __FILE__), + // m_base + // m_buffer + m_testAll(true), + m_logger(ReLogger::globalLogger()) { + m_base = testDir(); ReDirectory::deleteTree(m_base.str()); - m_base.append("dirtool"); - _mkdir(m_base.str(), ALLPERMS); + m_base.append("dirtool"); + _mkdir(m_base.str(), ALLPERMS); m_base.append(OS_SEPARATOR, -1); m_testAll = true; run(); ReDirectory::deleteTree(m_base.str(), true); } private: - ReByteBuffer m_base; + ReByteBuffer m_base; ReByteBuffer m_buffer; bool m_testAll; ReLogger* m_logger; private: - const char* makeDir(const char* relPath){ - m_buffer = m_base; - m_buffer.append(relPath); - m_buffer.replaceAll("/", 1, OS_SEPARATOR, -1); - _mkdir(m_buffer.str(), ALLPERMS); - struct stat info; - if (stat(m_buffer.str(), &info) != 0){ - logF(true, "cannot create dir %s", m_buffer.str()); - } - return m_buffer.str(); - } - void makeFile(const char* relPath){ - ReByteBuffer path(m_base); - path.append(relPath); - path.replaceAll("/", 1, OS_SEPARATOR, -1); - createFile(path.str(), relPath); - struct stat info; - if (stat(path.str(), &info) != 0){ - logF(true, "cannot create file %s", path.str()); - } - } - void initTree(){ - makeFile("1.txt"); - makeDir("dir1"); - makeDir("dir2"); + const char* makeDir(const char* relPath) { + m_buffer = m_base; + m_buffer.append(relPath); + m_buffer.replaceAll("/", 1, OS_SEPARATOR, -1); + _mkdir(m_buffer.str(), ALLPERMS); + struct stat info; + if (stat(m_buffer.str(), &info) != 0) { + logF(true, "cannot create dir %s", m_buffer.str()); + } + return m_buffer.str(); + } + void makeFile(const char* relPath) { + ReByteBuffer path(m_base); + path.append(relPath); + path.replaceAll("/", 1, OS_SEPARATOR, -1); + createFile(path.str(), relPath); + struct stat info; + if (stat(path.str(), &info) != 0) { + logF(true, "cannot create file %s", path.str()); + } + } + void initTree() { + makeFile("1.txt"); + makeDir("dir1"); + makeDir("dir2"); makeDir("dir1/cache"); - makeDir("dir1/dir1_1"); - makeDir("dir1/dir1_2"); - makeDir("dir1/dir1_2/dir1_2_1"); - makeFile("dir1/dir1_2/dir1_2_1/x1.txt"); - makeFile("dir1/dir1_2/dir1_2_1/x2.txt"); - makeFile("dir2/2.x"); - makeFile("dir1/cache/cache.txt"); - } - void run(){ + makeDir("dir1/dir1_1"); + makeDir("dir1/dir1_2"); + makeDir("dir1/dir1_2/dir1_2_1"); + makeFile("dir1/dir1_2/dir1_2_1/x1.txt"); + makeFile("dir1/dir1_2/dir1_2_1/x2.txt"); + makeFile("dir2/2.x"); + makeFile("dir1/cache/cache.txt"); + } + void run() { initTree(); - if (m_testAll){ + if (m_testAll) { testList2(); testToolStatistic(); testBasic(); @@ -87,115 +87,127 @@ private: } } // F:\temp\retestunit\dirtool - void testList2(){ + void testList2() { const char* argv[] = { "dt", "list", "-r", m_base.str(), NULL }; ReDirTools tools; tools.main(4, (char**) argv); } - void testList(){ - const char* argv[] = { "list", m_base.str(), NULL }; - ReDirList(m_logger).run(2, argv); - } - int secOfFileTime(ReFileTime_t data){ + void testList() { + const char* argv[] = { "list", m_base.str(), NULL }; + ReDirList(m_logger).run(2, argv); + } + int secOfFileTime(ReFileTime_t data) { #if defined __linux__ return data.tv_sec; #elif defined __WIN32__ return (int) ReDirStatus_t::filetimeToTime(&data); #endif } - void testCopyFile(){ + void testCopyFile() { #if defined __linux__ - ReByteBuffer src(m_base); - src.append("dir1/dir1_2/dir1_2_1/x1.txt"); - ReByteBuffer trg(testDir()); - trg.append("copy_x1.txt"); - ReByteBuffer buffer; + ReByteBuffer src(m_base); + src.append("dir1/dir1_2/dir1_2_1/x1.txt"); + ReByteBuffer trg(testDir()); + trg.append("copy_x1.txt"); + ReByteBuffer buffer; buffer.ensureSize(5); - ReDirSync::copyFile(src.str(), NULL, trg.str(), buffer, + ReDirSync::copyFile(src.str(), NULL, trg.str(), buffer, ReLogger::globalLogger()); - checkFileEqu(src.str(), trg.str()); + checkFileEqu(src.str(), trg.str()); #else - log(false, "testCopyFile not implemented"); + log(false, "testCopyFile not implemented"); #endif - } + } - void checkRelDate(ReFileTime_t absTime, int relTime){ - int diffNow = int(time(NULL) - secOfFileTime(absTime)); - int diff = diffNow * relTime < 0 ? diffNow + relTime : diffNow - relTime; - if (diff < 0) - diff = - diff; - checkT(diff < 2); - } - void testDirOptions(){ - class MyOptions : public ReDirOptions{ - public: - MyOptions() : ReDirOptions(s_empty, s_empty) {} - public: - int count() { return m_countCompoundUsage; } - const char** usage() { return m_compoundUsage; } - }; - static const char* usage1[] = { "line1", "line2", NULL }; - static const char* usage2[] = { "x1", "x2", "x3", NULL }; - MyOptions opts; - opts.initCompoundUsage(sizeof usage1 + sizeof usage2); - opts.addCompoundUsage(usage1); - opts.addCompoundUsage(usage2); - checkEqu(7, opts.count()); - checkEqu("line1", opts.usage()[0]); - checkEqu("line2", opts.usage()[1]); - checkEqu("x1", opts.usage()[2]); - checkEqu("x2", opts.usage()[3]); - checkEqu("x3", opts.usage()[4]); + void checkRelDate(ReFileTime_t absTime, int relTime) { + int diffNow = int(time(NULL) - secOfFileTime(absTime)); + int diff = + diffNow * relTime < 0 ? diffNow + relTime : diffNow - relTime; + if (diff < 0) + diff = -diff; + checkT(diff < 2); + } + void testDirOptions() { + class MyOptions: public ReDirOptions { + public: + MyOptions() : + ReDirOptions(s_empty, s_empty) { + } + public: + int count() { + return m_countCompoundUsage; + } + const char** usage() { + return m_compoundUsage; + } + }; + static const char* usage1[] = { "line1", "line2", NULL }; + static const char* usage2[] = { "x1", "x2", "x3", NULL }; + MyOptions opts; + opts.initCompoundUsage(sizeof usage1 + sizeof usage2); + opts.addCompoundUsage(usage1); + opts.addCompoundUsage(usage2); + checkEqu(7, opts.count()); + checkEqu("line1", opts.usage()[0]); + checkEqu("line2", opts.usage()[1]); + checkEqu("x1", opts.usage()[2]); + checkEqu("x2", opts.usage()[3]); + checkEqu("x3", opts.usage()[4]); - // local time: +3600 - const int DIFF = 3600; - checkEqu(tenYear + 24*60*60 - DIFF, secOfFileTime(opts.checkDate("1980.01.02"))); - checkEqu(tenYear + 24*60*60+3600-DIFF, secOfFileTime(opts.checkDate("1980.01.02/1"))); - checkEqu(tenYear + 24*60*60 + 2*3600 + 33*60 - DIFF, secOfFileTime(opts.checkDate("1980.01.02/02:33"))); - checkRelDate(opts.checkDate("now-3m"), 3*60); - checkRelDate(opts.checkDate("now-7h"), 7*60*60); - checkRelDate(opts.checkDate("now-5d"), 5*24*60*60); + // local time: +3600 + const int DIFF = 3600; + checkEqu(tenYear + 24 * 60 * 60 - DIFF, + secOfFileTime(opts.checkDate("1980.01.02"))); + checkEqu(tenYear + 24 * 60 * 60 + 3600 - DIFF, + secOfFileTime(opts.checkDate("1980.01.02/1"))); + checkEqu(tenYear + 24 * 60 * 60 + 2 * 3600 + 33 * 60 - DIFF, + secOfFileTime(opts.checkDate("1980.01.02/02:33"))); + checkRelDate(opts.checkDate("now-3m"), 3 * 60); + checkRelDate(opts.checkDate("now-7h"), 7 * 60 * 60); + checkRelDate(opts.checkDate("now-5d"), 5 * 24 * 60 * 60); - checkEqu(125ll, opts.checkSize("125")); - checkEqu(125ll, opts.checkSize("125b")); - checkEqu(3000ll, opts.checkSize("3k")); - checkEqu(3*1024ll, opts.checkSize("3K")); - checkEqu(4*1000*1000ll, opts.checkSize("4m")); - checkEqu(4*1024*1024ll, opts.checkSize("4M")); - checkEqu(5*1000*1000*1000ll, opts.checkSize("5g")); - checkEqu(5*1024*1024*1024ll, opts.checkSize("5G")); + checkEqu(125ll, opts.checkSize("125")); + checkEqu(125ll, opts.checkSize("125b")); + checkEqu(3000ll, opts.checkSize("3k")); + checkEqu(3 * 1024ll, opts.checkSize("3K")); + checkEqu(4 * 1000 * 1000ll, opts.checkSize("4m")); + checkEqu(4 * 1024 * 1024ll, opts.checkSize("4M")); + checkEqu(5 * 1000 * 1000 * 1000ll, opts.checkSize("5g")); + checkEqu(5 * 1024 * 1024 * 1024ll, opts.checkSize("5G")); - } - void checkSetFilterFromProgramArgs(){ - ReDirOptions opts(s_empty, s_empty); - opts.addStandardFilterOptions(); - const char* argv[] = { "x", "-y1980.01.02", "-o1980.01.03", - "-D5", "-d1", "-z1k", "-Z2M", "-p;*;-*~" - }; - ReDirEntryFilter_t filter; - opts.programArgsChangeable().init(sizeof argv / sizeof argv[0], argv); - opts.setFilterFromProgramArgs(filter); - // local time: +3600 - const int DIFF = 3600; - checkEqu(tenYear + 1*24*3600 - DIFF, secOfFileTime(filter.m_maxAge)); - checkEqu(tenYear + 2*24*3600 - DIFF, secOfFileTime(filter.m_minAge)); - checkEqu(5, (int) filter.m_maxDepth); - checkEqu(1, (int) filter.m_minDepth); - checkEqu(1000ll, filter.m_minSize); - checkEqu(2*1024*1024ll, filter.m_maxSize); - checkNN(filter.m_nodePatterns); - checkEqu(";*;-*~", filter.m_nodePatterns->patternString()); - } - void checkOneFile(const char* node, const char* parent, const ReHashList& hash){ - ReByteBuffer path, expected; - checkT(hash.get(ReByteBuffer(node), path)); - expected.set(parent, -1); - if (! expected.endsWith(OS_SEPARATOR)) - expected.append(OS_SEPARATOR); - if (! path.endsWith(expected.str(), -1)) - checkT(false); - } - void testBasic(){ + } + void checkSetFilterFromProgramArgs() { + ReDirOptions opts(s_empty, s_empty); + opts.addStandardFilterOptions(); + const char* argv[] = { "x", "-y1980.01.02", "-o1980.01.03", "-D5", + "-d1", "-z1k", "-Z2M", "-p;*;-*~" }; + ReDirEntryFilter_t filter; + opts.programArgsChangeable().init(sizeof argv / sizeof argv[0], argv); + opts.setFilterFromProgramArgs(filter); + // local time: +3600 + const int DIFF = 3600; + checkEqu(tenYear + 1 * 24 * 3600 - DIFF, + secOfFileTime(filter.m_maxAge)); + checkEqu(tenYear + 2 * 24 * 3600 - DIFF, + secOfFileTime(filter.m_minAge)); + checkEqu(5, (int ) filter.m_maxDepth); + checkEqu(1, (int ) filter.m_minDepth); + checkEqu(1000ll, filter.m_minSize); + checkEqu(2 * 1024 * 1024ll, filter.m_maxSize); + checkNN(filter.m_nodePatterns); + checkEqu(";*;-*~", filter.m_nodePatterns->patternString()); + } + void checkOneFile(const char* node, const char* parent, + const ReHashList& hash) { + ReByteBuffer path, expected; + checkT(hash.get(ReByteBuffer(node), path)); + expected.set(parent, -1); + if (!expected.endsWith(OS_SEPARATOR)) + expected.append(OS_SEPARATOR); + if (!path.endsWith(expected.str(), -1)) + checkT(false); + } + void testBasic() { ReTraverser traverser(m_base.str()); RePatternList patterns; // exclude */cache/* @@ -205,12 +217,10 @@ private: int level = 0; ReDirStatus_t* entry; ReHashList hash; - while( (entry = traverser.rawNextFile(level)) != NULL){ + while ((entry = traverser.rawNextFile(level)) != NULL) { hash.put(ReByteBuffer(entry->node(), -1), entry->m_path); - logF(false, "%d: %-12s %2d %s", - level, entry->node(), - int(entry->fileSize()), - entry->m_path.str()); + logF(false, "%d: %-12s %2d %s", level, entry->node(), + int(entry->fileSize()), entry->m_path.str()); } checkOneFile("x1.txt", "dir1_2_1", hash); checkOneFile("x2.txt", "dir1_2_1", hash); @@ -219,49 +229,50 @@ private: checkOneFile("dir1_2", "dir1", hash); checkF(hash.get("cache.txt", buffer)); } - void testDirStatistic(){ + void testDirStatistic() { ReDirStatistic stat(m_logger); const ReStringList& list = stat.calculate(m_base.str(), 1); ReByteBuffer buffer; - ReByteBuffer expected; + ReByteBuffer expected; log(false, list.join("\n", buffer).str()); checkEqu(3u, list.count()); - // "1 t:\temp\winfried\2\retestunit\dir1\n" - buffer.set(list.strOf(0), list.strLengthOf(0)); - checkT(buffer.startsWith("1\t")); - expected.set(m_base.str(), m_base.length()).append("dir1", -1) - .append(OS_SEPARATOR); - // .append(OS_SEPARATOR, -1) - checkT(buffer.endsWith(expected.str())); - - buffer.setLength(0); - const ReStringList& list2 = stat.calculate(m_base.str(), 1, formatWithSizeFilesAndDirs); + // "1 t:\temp\winfried\2\retestunit\dir1\n" + buffer.set(list.strOf(0), list.strLengthOf(0)); + checkT(buffer.startsWith("1\t")); + expected.set(m_base.str(), m_base.length()).append("dir1", -1).append( + OS_SEPARATOR); + // .append(OS_SEPARATOR, -1) + checkT(buffer.endsWith(expected.str())); + + buffer.setLength(0); + const ReStringList& list2 = stat.calculate(m_base.str(), 1, + formatWithSizeFilesAndDirs); log(false, list2.join("\n", buffer).str()); - - buffer.set(list.strOf(0), list.strLengthOf(0)); - checkT(buffer.startsWith(" 0.000074 MB 3 4\t")); - expected.set(m_base.str(), m_base.length()).append("dir1", -1) - .append(OS_SEPARATOR); - checkT(buffer.endsWith(expected.str())); - buffer.set(list.strOf(1), list.strLengthOf(1)); - checkT(buffer.startsWith(" 0.000008 MB 1 0\t")); - expected.set(m_base.str(), m_base.length()).append("dir2", -1) - .append(OS_SEPARATOR); - checkT(buffer.endsWith(expected.str())); + buffer.set(list.strOf(0), list.strLengthOf(0)); + checkT(buffer.startsWith(" 0.000074 MB 3 4\t")); + expected.set(m_base.str(), m_base.length()).append("dir1", -1).append( + OS_SEPARATOR); + checkT(buffer.endsWith(expected.str())); + + buffer.set(list.strOf(1), list.strLengthOf(1)); + checkT(buffer.startsWith(" 0.000008 MB 1 0\t")); + expected.set(m_base.str(), m_base.length()).append("dir2", -1).append( + OS_SEPARATOR); + checkT(buffer.endsWith(expected.str())); - buffer.set(list.strOf(2), list.strLengthOf(2)); - checkT(buffer.startsWith(" 0.000087 MB 5 6\t")); - expected.set(m_base.str(), m_base.length()); - } - /** + buffer.set(list.strOf(2), list.strLengthOf(2)); + checkT(buffer.startsWith(" 0.000087 MB 5 6\t")); + expected.set(m_base.str(), m_base.length()); + } + /** * Tests a file with a given context. * * @param filename name of the file to test * @param content expected content: each line must contain a '*', * separating the start of line and the end of line */ - void checkFile(ReByteBuffer& filename, const char* content){ + void checkFile(ReByteBuffer& filename, const char* content) { ReStringList current; current.readFromFile(filename.str()); ReStringList expected; @@ -269,88 +280,88 @@ private: checkEqu(expected.count(), current.count()); ReByteBuffer line; ReStringList cols; - for (size_t ix = 0; ix < current.count(); ix++){ + for (size_t ix = 0; ix < current.count(); ix++) { line.setLength(0).append(current.strOf(ix), -1); #if defined __WIN32__ line.replaceAll("/", 1, OS_SEPARATOR, 1); #endif cols.split(expected.strOf(ix), '*'); const char* col1 = cols.strOf(0); - if (! line.startsWith(col1)) + if (!line.startsWith(col1)) checkEqu(col1, line); const char* col2 = cols.strOf(1); - if (! line.endsWith(col2)){ + if (!line.endsWith(col2)) { checkEqu(col2, line); } } - } - void testTouch(){ + } + void testTouch() { ReByteBuffer nameCurrent; buildFilename("current", nameCurrent); ReByteBuffer optOutput("--output-file="); optOutput.append(nameCurrent); ReDirTools tools; const char* argv[] = { "dt", "touch", "-P;*;-cache", "-tr", "-p;*.txt", - "-m2015.03.28/10:21:31", optOutput.str(), m_base.str(), NULL }; + "-m2015.03.28/10:21:31", optOutput.str(), m_base.str(), NULL }; tools.main(8, (char**) argv); checkFile(nameCurrent, - "2015.03.28 10:21:31 *dirtool/1.txt\n" - "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n" - "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n" - "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n" - "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"); + "2015.03.28 10:21:31 *dirtool/1.txt\n" + "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n" + "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n" + "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n" + "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"); - const char* argv2[] = { "dt", "list", "-P;*;-cache", "-tr", "-p;*.txt", "-h", - optOutput.str(), m_base.str(), NULL }; + const char* argv2[] = { "dt", "list", "-P;*;-cache", "-tr", "-p;*.txt", + "-h", optOutput.str(), m_base.str(), NULL }; tools.main(8, (char**) argv2); checkFile(nameCurrent, - " 0.000005 2015.03.28 10:21:31 *dirtool/1.txt\n" - " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n" - " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n" - "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n" - "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"); + " 0.000005 2015.03.28 10:21:31 *dirtool/1.txt\n" + " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n" + " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n" + "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n" + "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"); } - void testBatch(){ + void testBatch() { ReByteBuffer nameCurrent; buildFilename("current", nameCurrent); ReByteBuffer optOutput("--output-file="); optOutput.append(nameCurrent); ReDirTools tools; - const char* argv[] = { "dt", "batch", "-P;*;-cache", "-td", "-cmyscript", - optOutput.str(), m_base.str(), NULL }; + const char* argv[] = { "dt", "batch", "-P;*;-cache", "-td", + "-cmyscript", optOutput.str(), m_base.str(), NULL }; tools.main(7, (char**) argv); #if defined __linux__ static const char* content = "#! /bin/sh*\n" - "myscript '*dirtool/dir1'\n" - "myscript '*dirtool/dir2'\n" - "myscript '*dirtool/dir1/dir1_1'\n" - "myscript '*dirtool/dir1/dir1_2'\n" - "myscript '*dirtool/dir1/cache'\n" - "myscript '*dirtool/dir1/dir1_2/dir1_2_1'\n" - "# === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) */sec\n" - "# === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"; + "myscript '*dirtool/dir1'\n" + "myscript '*dirtool/dir2'\n" + "myscript '*dirtool/dir1/dir1_1'\n" + "myscript '*dirtool/dir1/dir1_2'\n" + "myscript '*dirtool/dir1/cache'\n" + "myscript '*dirtool/dir1/dir1_2/dir1_2_1'\n" + "# === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) */sec\n" + "# === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"; #elif defined __WIN32__ static const char* content = "rem this batch is created by*dirtool\n" - "call myscript *dirtool\\dir1\"\n" - "call myscript *dirtool\\dir2\"\n" - "call myscript *dirtool\\dir1\\cache\"\n" - "call myscript *dirtool\\dir1\\dir1_1\"\n" - "call myscript *dirtool\\dir1\\dir1_2\"\n" - "call myscript *dirtool\\dir1\\dir1_2\\dir1_2_1\"\n" - "rem === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) *sec\n" - "rem === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"; + "call myscript *dirtool\\dir1\"\n" + "call myscript *dirtool\\dir2\"\n" + "call myscript *dirtool\\dir1\\cache\"\n" + "call myscript *dirtool\\dir1\\dir1_1\"\n" + "call myscript *dirtool\\dir1\\dir1_2\"\n" + "call myscript *dirtool\\dir1\\dir1_2\\dir1_2_1\"\n" + "rem === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) *sec\n" + "rem === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec"; #endif checkFile(nameCurrent, content); } - void testToolStatistic(){ + void testToolStatistic() { ReDirTools tools; const char* argv[] = { "dt", "stat", "-P;*;-cache", m_base.str(), "2" }; tools.main(5, (char**) argv); } - void testToolSync(){ + void testToolSync() { ReDirTools tools; ReByteBuffer source(m_base); source.append("dir1"); @@ -358,13 +369,13 @@ private: target.ensureLastChar(OS_SEPARATOR_CHAR); target.append("synctest", -1); _mkdir(target.str(), ALLPERMS); - const char* argv[] = { "dt", "sync", "-P;*;-cache", "-p;*.txt", - source.str(), target.str() }; + const char* argv[] = { "dt", "sync", "-P;*;-cache", "-p;*.txt", source + .str(), target.str() }; tools.main(6, (char**) argv); } }; extern void testReDirTools(void); -void testReDirTools(void){ +void testReDirTools(void) { TestReDirTools unit; } diff --git a/cunit/cuReDirectory.cpp b/cunit/cuReDirectory.cpp index 87f4df7..cf86066 100644 --- a/cunit/cuReDirectory.cpp +++ b/cunit/cuReDirectory.cpp @@ -8,13 +8,14 @@ */ #include "base/rebase.hpp" -class TestReDirectory : public ReTestUnit { +class TestReDirectory: public ReTestUnit { public: - TestReDirectory() : ReTestUnit("ReFileFinder", __FILE__){ + TestReDirectory() : + ReTestUnit("ReFileFinder", __FILE__) { run(); } private: - void run(){ + void run() { ReByteBuffer dir; dir.set(testDir(), -1); ReByteBuffer file1 = dir; @@ -46,6 +47,6 @@ private: }; extern void testReDirectory(void); -void testReDirectory(void){ +void testReDirectory(void) { TestReDirectory unit; } diff --git a/cunit/cuReException.cpp b/cunit/cuReException.cpp index 081ceae..d0ec904 100644 --- a/cunit/cuReException.cpp +++ b/cunit/cuReException.cpp @@ -8,57 +8,56 @@ */ #include "base/rebase.hpp" -class TestReException : public ReTestUnit, public ReVarArgTrigger { +class TestReException: public ReTestUnit, public ReVarArgTrigger { public: - TestReException() - : - ReTestUnit("ReException", __FILE__), - m_argNo(0), - m_maxNo(0) - { + TestReException() : + ReTestUnit("ReException", __FILE__), + m_argNo(0), + m_maxNo(0) { run(); } - virtual void newArg(int no, int maxNo){ + virtual void newArg(int no, int maxNo) { m_argNo = no; m_maxNo = maxNo; } private: - void run(){ - try{ + void run() { + try { throw ReException("ReException"); checkT(false); - } catch (ReException& e){ + } catch (ReException& e) { log(false, e.getMessage()); } - try{ + try { throw ReException("ReException", __FILE__, __LINE__); checkT(false); - } catch (ReException& e){ + } catch (ReException& e) { log(false, e.getMessage()); } - try{ + try { throw ReFormatException("ReFormatException", "format"); checkT(false); - } catch (ReException& e){ + } catch (ReException& e) { log(false, e.getMessage()); } - try{ - throw ReFormatException("ReFormatException", "format", __FILE__, __LINE__); + try { + throw ReFormatException("ReFormatException", "format", __FILE__, + __LINE__); checkT(false); - } catch (ReException& e){ + } catch (ReException& e) { log(false, e.getMessage()); } - try{ + try { throw ReBoundsException("myArray", 101, 100); checkT(false); - } catch (ReException& e){ + } catch (ReException& e) { log(false, e.getMessage()); } - try{ - throw ReBoundsException("myArray", -1, 0, __FILE__, __LINE__); + try { + throw ReBoundsException("myArray", -1, 0, __FILE__, __LINE__); checkT(false); - } catch (ReException& e){ + } catch (ReException& e) { log(false, e.getMessage()); } @@ -69,7 +68,7 @@ private: }; extern void testReException(void); -void testReException(void){ +void testReException(void) { TestReException unit; } diff --git a/cunit/cuReHashList.cpp b/cunit/cuReHashList.cpp index 4dbca67..69ed6b2 100644 --- a/cunit/cuReHashList.cpp +++ b/cunit/cuReHashList.cpp @@ -9,19 +9,20 @@ #include "base/rebase.hpp" #include "math/remath.hpp" -class TestReHashList : public ReTestUnit { +class TestReHashList: public ReTestUnit { public: - TestReHashList() : ReTestUnit("ReHashList", __FILE__){ + TestReHashList() : + ReTestUnit("ReHashList", __FILE__) { run(); } private: - void run(){ + void run() { massTest(); testBasic(); testNext(); } - void massTest(){ - const int maxKeys = 20*1000; + void massTest() { + const int maxKeys = 20 * 1000; const int minLength = 3; const int maxLength = 10; const int countGet = maxKeys * 50; @@ -34,9 +35,9 @@ private: int64_t start = timer(); int ix; int collisions = 0; - for(ix = 0; ix < maxKeys; ix++){ + for (ix = 0; ix < maxKeys; ix++) { rand.nextString(minLength, maxLength, key); - if (hash.get(key, value)){ + if (hash.get(key, value)) { value.appendChar('+'); collisions++; } else { @@ -46,20 +47,20 @@ private: } int duration1 = milliSecSince(start); start = timer(); - for (ix = 0; ix < countGet; ix++){ + for (ix = 0; ix < countGet; ix++) { int ix2 = rand.nextInt(maxKeys); list.get(ix2, key); checkT(hash.get(key, value)); checkT(value.startsWith(key.str(), key.length())); } int duration2 = milliSecSince(start); - logF(false, "hashlist: keys: %1d duration: %s get count: %d duration: %s collisions: %d", - maxKeys, key.setLength(0).appendMilliSec(duration1).str(), - countGet, value.setLength(0).appendMilliSec(duration2).str(), - collisions); + logF(false, + "hashlist: keys: %1d duration: %s get count: %d duration: %s collisions: %d", + maxKeys, key.setLength(0).appendMilliSec(duration1).str(), countGet, + value.setLength(0).appendMilliSec(duration2).str(), collisions); log(false, hash.status(value.setLength(0))); } - void testBasic(){ + void testBasic() { ReHashList hash; ReByteBuffer key, value; @@ -88,7 +89,7 @@ private: checkT(hash.get("ab", -1, value)); checkEqu("999", value); } - void testNext(){ + void testNext() { ReHashList hash; hash.put("4", "2"); hash.put("1", "8"); @@ -98,7 +99,7 @@ private: int flagsVal = 0; ReArrayPosition pos; ReByteBuffer key, value; - while(hash.next(pos, &key, &value)){ + while (hash.next(pos, &key, &value)) { int x = atol(key.buffer()); int y = atol(value.buffer()); checkEqu(8, x * y); @@ -111,6 +112,6 @@ private: }; extern void testReHashList(void); -void testReHashList(void){ +void testReHashList(void) { TestReHashList unit; } diff --git a/cunit/cuReI18N.cpp b/cunit/cuReI18N.cpp index 23a5bba..ceaaf58 100644 --- a/cunit/cuReI18N.cpp +++ b/cunit/cuReI18N.cpp @@ -8,24 +8,23 @@ */ #include "base/rebase.hpp" -class TestReI18N : public ReTestUnit { +class TestReI18N: public ReTestUnit { public: - TestReI18N() - : - ReTestUnit("ReI18N", __FILE__) - { + TestReI18N() : + ReTestUnit("ReI18N", __FILE__) { run(); } private: - void run(){ + void run() { checkEqu("this is a test", i18n("this is a test")); - checkEqu("one: 1 two: 2", i18nf("one: $1 two: $2").arg(1).arg(2).asCString()); + checkEqu("one: 1 two: 2", + i18nf("one: $1 two: $2").arg(1).arg(2).asCString()); } }; extern void testReI18N(void); -void testReI18N(void){ +void testReI18N(void) { TestReI18N unit; } diff --git a/cunit/cuReLogger.cpp b/cunit/cuReLogger.cpp index fff80a0..15e94b3 100644 --- a/cunit/cuReLogger.cpp +++ b/cunit/cuReLogger.cpp @@ -8,29 +8,32 @@ */ #include "base/rebase.hpp" -class TestReLogger : public ReTestUnit { +class TestReLogger: public ReTestUnit { public: - TestReLogger() : ReTestUnit("ReLogger", __FILE__){ + TestReLogger() : + ReTestUnit("ReLogger", __FILE__) { run(); } private: - void run(){ + void run() { ReStreamAppender app1(stdout); app1.setMode(CAT_ALL, CAT_ALL, CAT_ALL, GRAN_ALL); ReLogger logger(false); logger.addAppender(&app1); log(false, "2 Errors and a warning:"); - logger.say(LOG_ABORT | CAT_TEST | GRAN_TRACE, __LINE__, "abort");; + logger.say(LOG_ABORT | CAT_TEST | GRAN_TRACE, __LINE__, "abort"); + ; logger.say(LOG_ERROR | CAT_TEST, __LINE__, "error"); logger.say(LOG_WARNING | CAT_TEST, __LINE__, "warning"); - logger.sayF(CAT_TEST, __LINE__, "Two: $1 eleven: $021").arg(2).arg(1).end(); + logger.sayF(CAT_TEST, __LINE__, "Two: $1 eleven: $021").arg(2).arg(1) + .end(); globalLogger()->say(CAT_LIB, __LINE__, "globalLogger()"); } }; extern void testReLogger(void); -void testReLogger(void){ +void testReLogger(void) { TestReLogger unit; } diff --git a/cunit/cuReMD5.cpp b/cunit/cuReMD5.cpp index 36af4cc..6894de8 100644 --- a/cunit/cuReMD5.cpp +++ b/cunit/cuReMD5.cpp @@ -11,35 +11,34 @@ #include "math/remath.hpp" #include "math/md5.hpp" -class TestReMd5 : public ReTestUnit { +class TestReMd5: public ReTestUnit { public: - TestReMd5() : ReTestUnit("ReMD5", __FILE__){ + TestReMd5() : + ReTestUnit("ReMD5", __FILE__) { run(); } private: - void run(){ + void run() { testBase(); testSpeed(); testLong(); testBig(); } - void testBase(){ + void testBase() { ReMD5 md5; - const char* text = "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVEXYZ01234567890\n"; - md5.update((const uint8_t*)text, strlen(text)); - checkEqu("c0a278c051a6898f6ad05da7fa80a1c4", - md5.hexDigest()); + const char* text = + "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVEXYZ01234567890\n"; + md5.update((const uint8_t*) text, strlen(text)); + checkEqu("c0a278c051a6898f6ad05da7fa80a1c4", md5.hexDigest()); md5.reset(); text = "The quick brown fox jumps over the lazy dog"; md5.update((const uint8_t*) text, -1); - checkEqu("9e107d9d372bb6826bd81d3542a419d6", - md5.hexDigest()); + checkEqu("9e107d9d372bb6826bd81d3542a419d6", md5.hexDigest()); md5.reset(); - md5.update((const uint8_t*)"", 0); - checkEqu("d41d8cd98f00b204e9800998ecf8427e", - md5.hexDigest()); + md5.update((const uint8_t*) "", 0); + checkEqu("d41d8cd98f00b204e9800998ecf8427e", md5.hexDigest()); } - int testOneLong(ReByteBuffer& text, int seed2 = 0){ + int testOneLong(ReByteBuffer& text, int seed2 = 0) { ReMD5 md5; int rc = 0; ReShiftRandom random; @@ -51,7 +50,7 @@ private: int max2 = text.length() / 20; if (max2 < 1) max2 = random.nextInt(20); - while(text.length() > 0){ + while (text.length() > 0) { int part = random.nextInt(32, 32 + 1 + max2); if (part > (int) text.length()) part = text.length(); @@ -62,31 +61,32 @@ private: checkEqu(digest, md5.hexDigest()); return rc; } - void testLong(){ - ReByteBuffer text("01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVEXYZ0123456789001234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVEXYZ01234567890\n"); - for (int ii = 178 - 69 + 1; ii > 0; ii--){ + void testLong() { + ReByteBuffer text( + "01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVEXYZ0123456789001234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVEXYZ01234567890\n"); + for (int ii = 178 - 69 + 1; ii > 0; ii--) { text.setLength(ii); testOneLong(text, 200 * ii + 0x47111); } } - void testBig(){ + void testBig() { ReByteBuffer text; ReShiftRandom random; int64_t start = timer(); int count = 1000; int parts = 0; int sumLength = 0; - for (int ii = 0; ii < count; ii++){ + for (int ii = 0; ii < count; ii++) { random.nextString(10, 20000, text); sumLength += text.length(); parts += testOneLong(text, 333 * ii + 0x55221); } - printf("count: %d updates: %d avg length: %d duration: %s\n", - count, parts, sumLength / count, - ReByteBuffer("").appendMilliSec(milliSecSince(start)).str()); + printf("count: %d updates: %d avg length: %d duration: %s\n", count, + parts, sumLength / count, + ReByteBuffer("").appendMilliSec(milliSecSince(start)).str()); } - void testSpeed(){ - int max = 1024*1024*50; + void testSpeed() { + int max = 1024 * 1024 * 50; ReByteBuffer buffer; buffer.ensureSize(max); buffer.setLength(max - 1); @@ -94,26 +94,27 @@ private: ReMD5 md5; int passes = 20; int64_t start = timer(); - for (int ii = 0; ii < passes; ii++){ + for (int ii = 0; ii < passes; ii++) { md5.reset(); md5.update((uint8_t*) buffer.str(), max - 1); } int duration = milliSecSince(start); if (duration == 0) duration = 1; - printf("%s endian size: %.1f MiByte count: %d rate: %.2f MiB/sec duration: %s\n", + printf( + "%s endian size: %.1f MiByte count: %d rate: %.2f MiB/sec duration: %s\n", #if defined __LITTLE_ENDIAN__ - "little", + "little", #else - "big", + "big", #endif - max / 1024.0 / 1024, passes, - max / 1024.0 / 1024 * 1000 * passes / duration, - ReByteBuffer("").appendMilliSec(duration).str()); + max / 1024.0 / 1024, passes, + max / 1024.0 / 1024 * 1000 * passes / duration, + ReByteBuffer("").appendMilliSec(duration).str()); } }; extern void testReMD5(void); -void testReMD5(void){ +void testReMD5(void) { TestReMd5 unit; } diff --git a/cunit/cuReMatcher.cpp b/cunit/cuReMatcher.cpp index bff5965..699643d 100644 --- a/cunit/cuReMatcher.cpp +++ b/cunit/cuReMatcher.cpp @@ -15,24 +15,24 @@ * The latest sources: https://github.com/republib */ - #include "base/rebase.hpp" #include "string/restring.hpp" -class TestReMatcher : public ReTestUnit { +class TestReMatcher: public ReTestUnit { public: - TestReMatcher() : ReTestUnit("ReMatcher", __FILE__){ + TestReMatcher() : + ReTestUnit("ReMatcher", __FILE__) { run(); } private: - void run(){ + void run() { testPatternList(); testMatch(); testSearch(); testMatchManyStars(); testSearchManyStars(); } - void testPatternList(){ + void testPatternList() { RePatternList list; list.set(";*.cpp;-cu*;*.hpp;", true); checkT(list.match("a.hpp")); @@ -45,7 +45,7 @@ private: checkT(list.match("a.hpp")); checkF(list.match("a.hpp~")); } - void testMatch(){ + void testMatch() { ReSimpleMatcher matcher("abc*.x"); matcher.setIgnoreCase(false); @@ -65,7 +65,7 @@ private: checkT(matcher.match("abc.X")); checkT(matcher.match("aBcdef.X")); } - void testMatchManyStars(){ + void testMatchManyStars() { ReSimpleMatcher matcher("a*b*c*x"); matcher.setIgnoreCase(false); @@ -111,7 +111,7 @@ private: checkF(matcher.match("")); checkF(matcher.match("x")); } - void testSearch(){ + void testSearch() { ReSimpleMatcher matcher("abc*.x"); matcher.setIgnoreCase(false); @@ -154,7 +154,7 @@ private: checkT(matcher.search("resT")); checkF(matcher.search("xyz")); } - void testSearchManyStars(){ + void testSearchManyStars() { ReSimpleMatcher matcher("*a*b*c*x*"); matcher.setIgnoreCase(false); @@ -171,9 +171,7 @@ private: }; extern void testReMatcher(void); -void testReMatcher(void){ +void testReMatcher(void) { TestReMatcher unit; } - - diff --git a/cunit/cuReProgramArgs.cpp b/cunit/cuReProgramArgs.cpp index 692d4ca..98faf92 100644 --- a/cunit/cuReProgramArgs.cpp +++ b/cunit/cuReProgramArgs.cpp @@ -8,76 +8,82 @@ */ #include "base/rebase.hpp" -class TestReProgramArgs : public ReTestUnit { +class TestReProgramArgs: public ReTestUnit { public: - TestReProgramArgs() - : - ReTestUnit("ReProgramArgs", __FILE__) - { + TestReProgramArgs() : + ReTestUnit("ReProgramArgs", __FILE__) { run(); } private: - void run(){ + void run() { testLong(); testShort(); - testWrong(); - testSetUsage(); + testWrong(); + testSetUsage(); } - void testWrong(){ - ReProgramArgs args("test","example"); + void testWrong() { + ReProgramArgs args("test", "example"); args.addBool("boolarg", "This is a boolean arg", 'b', "boolval", false); - try { - const char* argv[] = { "test", "-v" }; - args.init(2, argv); - checkF(true); - } catch (ReOptionException& exc) { - checkEqu("Unknown option: v", exc.getMessage()); - } - } - void createExpectedShortHelp(const char* filename){ + try { + const char* argv[] = { "test", "-v" }; + args.init(2, argv); + checkF(true); + } catch (ReOptionException& exc) { + checkEqu("Unknown option: v", exc.getMessage()); + } + } + void createExpectedShortHelp(const char* filename) { createFile(filename, -"test \n" -"This tests the usage of ReProgramArgs\n" -"\n" -":\n" -"-B or --boolval2\n" -" This is the 2nd boolean arg\n" -"-x or --boolval3\n" -" This is the 3rd boolean arg\n" -"-Y or --boolval4\n" -" This is the 4th boolean arg\n" -"-S[] or --estring=[] Default value: empty\n" -" This string may be empty\n" -"-U[] or --estring2=[] Default value: undef2\n" -" This 2nd string may be empty\n" -"-i or --intval= Default value: 9\n" -" This is an integer arg\n" -"-I or --intval= Default value: 1000\n" -" This is the 2nd integer arg\n" -"-s or --string= Default value: 'abc'\n" -" This string must be non empty\n" -"-u or --string2= Default value: 'undef'\n" -" This 2nd string must be non empty\n" -"Example(s):\n" -"? -b+ -B- file dir\n" -"\ttest of an example\n" -"+++ Not really an error!\n" - ); - } - void testShort(){ - ReProgramArgs args("test \nThis tests the usage of ReProgramArgs", - "$0 -b+ -B- file dir\n\ttest of an example"); + "test \n" + "This tests the usage of ReProgramArgs\n" + "\n" + ":\n" + "-B or --boolval2\n" + " This is the 2nd boolean arg\n" + "-x or --boolval3\n" + " This is the 3rd boolean arg\n" + "-Y or --boolval4\n" + " This is the 4th boolean arg\n" + "-S[] or --estring=[] Default value: empty\n" + " This string may be empty\n" + "-U[] or --estring2=[] Default value: undef2\n" + " This 2nd string may be empty\n" + "-i or --intval= Default value: 9\n" + " This is an integer arg\n" + "-I or --intval= Default value: 1000\n" + " This is the 2nd integer arg\n" + "-s or --string= Default value: 'abc'\n" + " This string must be non empty\n" + "-u or --string2= Default value: 'undef'\n" + " This 2nd string must be non empty\n" + "Example(s):\n" + "? -b+ -B- file dir\n" + "\ttest of an example\n" + "+++ Not really an error!\n"); + } + void testShort() { + ReProgramArgs args( + "test \nThis tests the usage of ReProgramArgs", + "$0 -b+ -B- file dir\n\ttest of an example"); args.addBool("boolarg", "This is a boolean arg", 'b', "boolval", false); - args.addBool("boolarg2", "This is the 2nd boolean arg", 'B', "boolval2", true); - args.addBool("boolarg3", "This is the 3rd boolean arg", 'x', "boolval3", false); - args.addBool("boolarg4", "This is the 4th boolean arg", 'Y', "boolval4", true); + args.addBool("boolarg2", "This is the 2nd boolean arg", 'B', "boolval2", + true); + args.addBool("boolarg3", "This is the 3rd boolean arg", 'x', "boolval3", + false); + args.addBool("boolarg4", "This is the 4th boolean arg", 'Y', "boolval4", + true); args.addInt("intarg", "This is an integer arg", 'i', "intval", 9); - args.addInt("intarg2", "This is the 2nd integer arg", 'I', "intval", 1000); - args.addString("stringarg", "This string must be non empty", 's', "string", false, "abc"); - args.addString("stringarg2", "This 2nd string must be non empty", 'u', "string2", false, "undef"); - args.addString("estringarg", "This string may be empty", 'S', "estring", true, "empty"); - args.addString("estringarg2", "This 2nd string may be empty", 'U', "estring2", true, "undef2"); + args.addInt("intarg2", "This is the 2nd integer arg", 'I', "intval", + 1000); + args.addString("stringarg", "This string must be non empty", 's', + "string", false, "abc"); + args.addString("stringarg2", "This 2nd string must be non empty", 'u', + "string2", false, "undef"); + args.addString("estringarg", "This string may be empty", 'S', "estring", + true, "empty"); + args.addString("estringarg2", "This 2nd string may be empty", 'U', + "estring2", true, "undef2"); checkF(args.getBool("boolarg")); checkEqu(9, args.getInt("intarg")); @@ -85,9 +91,8 @@ private: checkEqu("empty", args.getString("estringarg", buffer)); checkEqu("abc", args.getString("stringarg", buffer)); - const char* vector[] = { - "testprog", "-bB+i123", "-S", "-x-", "-Y+", "-s", "2nd string", "arg1", "arg2" - }; + const char* vector[] = { "testprog", "-bB+i123", "-S", "-x-", "-Y+", + "-s", "2nd string", "arg1", "arg2" }; args.init(sizeof vector / sizeof vector[0], vector); checkEqu("testprog", args.getProgramName()); @@ -108,7 +113,7 @@ private: ReByteBuffer fn; FILE* fp = fopen(buildFilename("help.tmp.txt", fn), "w"); checkF(fp == NULL); - if (fp != NULL){ + if (fp != NULL) { args.help("Not really an error!", false, fp); fclose(fp); ReByteBuffer fnExpected; @@ -117,73 +122,77 @@ private: checkFileEqu(fnExpected.str(), fn.str()); } } - void testSetUsage(){ - class MyArgs : public ReProgramArgs { - public: - MyArgs() : ReProgramArgs("", "example") {} - public: - ReStringList& usage() { return m_usage; } - }; - MyArgs args; - const char* usage[] = { "x1", "x2", NULL }; - args.setUsage(usage); - checkEqu("x1", args.usage().strOf(0)); - checkEqu("x2", args.usage().strOf(1)); - } - void createExpectedLongHelp(const char* filename){ - createFile(filename, -"test \n" -"This tests the usage of ReProgramArgs\n" -"\n" -":\n" -"--boolval2\n" -" This is the 2nd boolean arg\n" -"-x or --boolval3\n" -" This is the 3rd boolean arg\n" -"--boolval4\n" -" This is the 3rd boolean arg\n" -"--estring=[] Default value: empty\n" -" This string may be empty\n" -"-U[] or --estring2=[] Default value: undef2\n" -" This 2nd string may be empty\n" -"-V[] or --estring3=[] Default value: undef3\n" -" This 3thrd string may be empty\n" -"-i or --intval= Default value: 9\n" -" This is an integer arg\n" -"-s or --string= Default value: 'abc'\n" -" This string must be non empty\n" -"Example(s):\n" -"test -intval=10 --boolval=t\n" - ); - } - void testLong(){ - const char* call[] = { - "test ", - "This tests the usage of ReProgramArgs", - NULL + void testSetUsage() { + class MyArgs: public ReProgramArgs { + public: + MyArgs() : + ReProgramArgs("", "example") { + } + public: + ReStringList& usage() { + return m_usage; + } }; - const char* examples[] = { "test -intval=10 --boolval=t", NULL}; + MyArgs args; + const char* usage[] = { "x1", "x2", NULL }; + args.setUsage(usage); + checkEqu("x1", args.usage().strOf(0)); + checkEqu("x2", args.usage().strOf(1)); + } + void createExpectedLongHelp(const char* filename) { + createFile(filename, + "test \n" + "This tests the usage of ReProgramArgs\n" + "\n" + ":\n" + "--boolval2\n" + " This is the 2nd boolean arg\n" + "-x or --boolval3\n" + " This is the 3rd boolean arg\n" + "--boolval4\n" + " This is the 3rd boolean arg\n" + "--estring=[] Default value: empty\n" + " This string may be empty\n" + "-U[] or --estring2=[] Default value: undef2\n" + " This 2nd string may be empty\n" + "-V[] or --estring3=[] Default value: undef3\n" + " This 3thrd string may be empty\n" + "-i or --intval= Default value: 9\n" + " This is an integer arg\n" + "-s or --string= Default value: 'abc'\n" + " This string must be non empty\n" + "Example(s):\n" + "test -intval=10 --boolval=t\n"); + } + void testLong() { + const char* call[] = { "test ", + "This tests the usage of ReProgramArgs", + NULL }; + const char* examples[] = { "test -intval=10 --boolval=t", NULL }; ReProgramArgs args(call, examples); args.addBool("boolarg", "This is a boolean arg", 'b', "boolval", false); char none = ReProgramArgs::HIDDEN_SHORT_NAME; - args.addBool("boolarg2", "This is the 2nd boolean arg", none, "boolval2", true); - args.addBool("boolarg3", "This is the 3rd boolean arg", 'x', "boolval3", false); - args.addBool("boolarg4", "This is the 3rd boolean arg", none, "boolval4", true); + args.addBool("boolarg2", "This is the 2nd boolean arg", none, + "boolval2", true); + args.addBool("boolarg3", "This is the 3rd boolean arg", 'x', "boolval3", + false); + args.addBool("boolarg4", "This is the 3rd boolean arg", none, + "boolval4", true); args.addInt("intarg", "This is an integer arg", 'i', "intval", 9); - args.addString("stringarg", "This string must be non empty", 's', "string", false, "abc"); - args.addString("estringarg", "This string may be empty", none, "estring", true, "empty"); - args.addString("estringarg2", "This 2nd string may be empty", 'U', "estring2", true, "undef2"); - args.addString("estringarg3", "This 3thrd string may be empty", 'V', "estring3", true, "undef3"); + args.addString("stringarg", "This string must be non empty", 's', + "string", false, "abc"); + args.addString("estringarg", "This string may be empty", none, + "estring", true, "empty"); + args.addString("estringarg2", "This 2nd string may be empty", 'U', + "estring2", true, "undef2"); + args.addString("estringarg3", "This 3thrd string may be empty", 'V', + "estring3", true, "undef3"); ReByteBuffer buffer; - const char* vector[] = { - "testprog", - "--boolval", "--boolval2=true", "--boolval3=f", "--boolval4=0", - "--intval=3", - "--string=x y", "--estring=", "--estring2=not empty", - "arg1", "arg2" - }; + const char* vector[] = { "testprog", "--boolval", "--boolval2=true", + "--boolval3=f", "--boolval4=0", "--intval=3", "--string=x y", + "--estring=", "--estring2=not empty", "arg1", "arg2" }; args.init(sizeof vector / sizeof vector[0], vector); checkEqu("testprog", args.getProgramName()); @@ -201,7 +210,7 @@ private: ReByteBuffer fn; FILE* fp = fopen(buildFilename("help.tmp.txt", fn), "w"); checkT(fp != NULL); - if (fp){ + if (fp) { args.help(NULL, false, fp); fclose(fp); ReByteBuffer fnExpected; @@ -212,6 +221,6 @@ private: }; extern void testReProgramArgs(void); -void testReProgramArgs(void){ +void testReProgramArgs(void) { TestReProgramArgs unit; } diff --git a/cunit/cuReRandomizer.cpp b/cunit/cuReRandomizer.cpp index 666c46e..cc91dd2 100644 --- a/cunit/cuReRandomizer.cpp +++ b/cunit/cuReRandomizer.cpp @@ -9,20 +9,19 @@ #include "base/rebase.hpp" #include "math/remath.hpp" -class TestReRandomizer : public ReTestUnit { +class TestReRandomizer: public ReTestUnit { public: TestReRandomizer() : - ReTestUnit("ReRandomizer", __FILE__) - { + ReTestUnit("ReRandomizer", __FILE__) { run(); } private: - void run(){ + void run() { testNextInt64Repeater(); testNextInt64(); } - void testNextInt64Repeater(){ + void testNextInt64Repeater() { ReCongruentialGenerator rand; const int MAX = 16; time_t start = time(NULL); @@ -30,13 +29,13 @@ private: for (int ix = 0; ix < MAX; ix++) field[ix] = rand.nextInt64(); rand.reset(); - for (int ix = 0; ix < MAX; ix++){ + for (int ix = 0; ix < MAX; ix++) { int64_t current = rand.nextInt64(); if (field[ix] != current) checkEqu(field[ix], current); } } - void testNextInt64(){ + void testNextInt64() { ReCongruentialGenerator rand; const int MAX = 16; time_t start = time(NULL); @@ -44,9 +43,9 @@ private: for (int ix = 0; ix < MAX; ix++) field[ix] = rand.nextInt64(ix + 10); rand.reset(); - for (int ix = 0; ix < MAX; ix++){ + for (int ix = 0; ix < MAX; ix++) { checkEqu(field[ix], rand.nextInt64(ix + 10)); - if (! (field[ix] >= 0 && field[ix] <= ix + 10)) + if (!(field[ix] >= 0 && field[ix] <= ix + 10)) checkT(false); } time_t diff = time(NULL) - start; @@ -54,7 +53,7 @@ private: }; extern void testReRandomizer(void); -void testReRandomizer(void){ +void testReRandomizer(void) { TestReRandomizer unit; } diff --git a/cunit/cuReSeqArray.cpp b/cunit/cuReSeqArray.cpp index 942aa75..1c0b174 100644 --- a/cunit/cuReSeqArray.cpp +++ b/cunit/cuReSeqArray.cpp @@ -8,13 +8,14 @@ */ #include "base/rebase.hpp" -class TestReSeqList : public ReTestUnit { +class TestReSeqList: public ReTestUnit { public: - TestReSeqList() : ReTestUnit("ReSeqArray", __FILE__){ + TestReSeqList() : + ReTestUnit("ReSeqArray", __FILE__) { run(); } private: - void run(){ + void run() { testBinSearch2(); testBinSearch(); testSorted(); @@ -24,14 +25,15 @@ private: testBase(); testRemove(); } - void checkElement(ReSeqArray& list, ReSeqArray::Index index, const char* value, ReSeqArray::Tag expectedTag){ + void checkElement(ReSeqArray& list, ReSeqArray::Index index, + const char* value, ReSeqArray::Tag expectedTag) { ReByteBuffer buffer; ReSeqArray::Tag tag; checkT(list.get(index, buffer, &tag)); checkIEqu(value, buffer.str()); checkEqu(expectedTag, tag); } - void testBinSearch(){ + void testBinSearch() { ReSeqArray list; list.setIgnoreCase(true); ReByteBuffer value, expectedValue; @@ -65,20 +67,20 @@ private: checkF(list.binarySearch("cee", -1, index, NULL)); checkEqu(ReSeqArray::Index(5), index); } - void testBinSearch2(){ + void testBinSearch2() { ReSeqArray list; ReSeqArray::Index index; ReByteBuffer value; list.setSorted(true); value = "ab"; - for (int count = 2; count < 16; count++){ + for (int count = 2; count < 16; count++) { list.clear(); - for (int ix = 0; ix < count; ix++){ + for (int ix = 0; ix < count; ix++) { value.setLength(2); value.buffer()[0] = 'a' + ix; - list.add(ix, value.str(), -1, (ReSeqArray::Tag) ix*10); + list.add(ix, value.str(), -1, (ReSeqArray::Tag) ix * 10); } - for (int ix = 0; ix <= count; ix++){ + for (int ix = 0; ix <= count; ix++) { if (count == 2 && ix == 2) ix = 2; value.setLength(2); @@ -86,7 +88,7 @@ private: value.buffer()[1] = 'a'; checkF(list.binarySearch(value.str(), -1, index)); checkEqu(ReSeqArray::Index(ix), index); - if (ix > 0){ + if (ix > 0) { value.setLength(3); value.buffer()[0] = 'a' + ix - 1; value.buffer()[1] = 'b'; @@ -98,7 +100,7 @@ private: } } } - void testSorted(){ + void testSorted() { ReSeqArray list; list.setIgnoreCase(true); ReByteBuffer value, expectedValue; @@ -128,7 +130,7 @@ private: checkT(list.binarySearch("cde", -1, index, &tag)); checkEqu(4u, index); } - void testIgnoreCase(){ + void testIgnoreCase() { ReSeqArray list; list.setIgnoreCase(true); ReByteBuffer value, expectedValue; @@ -138,14 +140,14 @@ private: checkEqu(0U, list.find("AbC", -1)); checkEqu(1U, list.find("BCD", -1)); } - void testAdd(){ + void testAdd() { ReSeqArray list; ReByteBuffer value, expectedValue; ReSeqArray::Tag tag = 0; ReSeqArray::Tag expectedTag = 0; size_t maxIx = 64; - list.setSizes(8, 1); - for (size_t ix = 0; ix < maxIx; ix++){ + list.setSizes(8, 1); + for (size_t ix = 0; ix < maxIx; ix++) { expectedTag = (int64_t(1) << ix); expectedValue.append("x", 1); list.add(-1, expectedValue.str(), -1, expectedTag); @@ -156,7 +158,7 @@ private: checkEqu(expectedTag, tag); } expectedValue.setLength(0); - for (size_t ix = 0; ix < maxIx; ix++){ + for (size_t ix = 0; ix < maxIx; ix++) { expectedTag = (1ll << ix); expectedValue.appendChar('x'); checkT(list.get(ix, value, &tag)); @@ -165,14 +167,14 @@ private: } } - void testFind(){ + void testFind() { ReSeqArray list; ReByteBuffer value, expectedValue; ReSeqArray::Tag tag = 0; ReSeqArray::Tag expectedTag = 0; size_t maxIx = 13; - for (size_t ix = 0; ix < maxIx; ix++){ - expectedTag = 10*ix; + for (size_t ix = 0; ix < maxIx; ix++) { + expectedTag = 10 * ix; expectedValue.appendChar('x'); list.add(-1, expectedValue.str(), -1, expectedTag); checkEqu(ix + 1, list.count()); @@ -183,16 +185,18 @@ private: } //list.dump(stdout); expectedValue.setLength(0); - for (size_t ix = 0; ix < maxIx; ix++){ + for (size_t ix = 0; ix < maxIx; ix++) { expectedTag = -1; expectedValue.appendChar('x'); if (ix >= 4) expectedTag = -1; - checkEqu(ix, list.find(expectedValue.str(), expectedValue.length(), &expectedTag)); - checkEqu(int(10*ix), (int) expectedTag); + checkEqu(ix, + list.find(expectedValue.str(), expectedValue.length(), + &expectedTag)); + checkEqu(int(10 * ix), (int ) expectedTag); } } - void testBase(){ + void testBase() { ReSeqArray list; ReByteBuffer value; ReSeqArray::Tag tag = 0; @@ -207,7 +211,7 @@ private: checkEqu(1u, list.count()); checkT(list.get(0, value, &tag)); checkEqu("123", value); - checkEqu((int64_t) 0x3344556633445566ll, tag); + checkEqu((int64_t ) 0x3344556633445566ll, tag); list.add(-1, "ab", -1, 0x345678abcdef3344ll); checkEqu(2u, list.count()); @@ -243,7 +247,7 @@ private: checkEqu(0u, list.count()); checkF(list.get(0, value)); } - void testRemove(){ + void testRemove() { ReSeqArray list; ReByteBuffer value; ReSeqArray::Tag tag = 0; @@ -265,7 +269,6 @@ private: checkEqu("ghi", value); checkEqu(300ll, tag); - list.remove(1); checkEqu(2u, list.count()); list.get(0, value, &tag); @@ -285,6 +288,6 @@ private: }; extern void testReSeqArray(void); -void testReSeqArray(void){ +void testReSeqArray(void) { TestReSeqList unit; } diff --git a/cunit/cuReStringList.cpp b/cunit/cuReStringList.cpp index 09095c4..bf86bb0 100644 --- a/cunit/cuReStringList.cpp +++ b/cunit/cuReStringList.cpp @@ -8,13 +8,14 @@ */ #include "base/rebase.hpp" -class TestReStringList : public ReTestUnit { +class TestReStringList: public ReTestUnit { public: - TestReStringList() : ReTestUnit("ReStringList", __FILE__){ + TestReStringList() : + ReTestUnit("ReStringList", __FILE__) { run(); } private: - void run(){ + void run() { testAppendByteBuffer(); testBase(); testReplace(); @@ -22,12 +23,12 @@ private: testEqu(); testFile(); } - void testAppendByteBuffer(){ + void testAppendByteBuffer() { ReStringList list; ReByteBuffer line; line.set("Hi", -1); - list.append(line, 99); - line.append("!", -1); + list.append(line, 99); + line.append("!", -1); list.append(line, -5); checkEqu(2u, list.count()); @@ -39,45 +40,45 @@ private: checkN(list.strOf(2)); } - void testReplace(){ + void testReplace() { ReStringList list; list.append("123", 100); - checkEqu((int64_t) 100, list.tagOf(0)); + checkEqu((int64_t ) 100, list.tagOf(0)); list.append("2", 200); - checkEqu((int64_t) 100, list.tagOf(0)); - checkEqu((int64_t) 200, list.tagOf(1)); + checkEqu((int64_t ) 100, list.tagOf(0)); + checkEqu((int64_t ) 200, list.tagOf(1)); list.append("34", 300); - checkEqu((int64_t) 100, list.tagOf(0)); - checkEqu((int64_t) 200, list.tagOf(1)); - checkEqu((int64_t) 300, list.tagOf(2)); + checkEqu((int64_t ) 100, list.tagOf(0)); + checkEqu((int64_t ) 200, list.tagOf(1)); + checkEqu((int64_t ) 300, list.tagOf(2)); list.replace(0, "1", 111); checkEqu("1", list.strOf(0)); - checkEqu((int64_t) 111, list.tagOf(0)); - checkEqu((int64_t) 200, list.tagOf(1)); - checkEqu((int64_t) 300, list.tagOf(2)); + checkEqu((int64_t ) 111, list.tagOf(0)); + checkEqu((int64_t ) 200, list.tagOf(1)); + checkEqu((int64_t ) 300, list.tagOf(2)); list.replace(1, "124", 222); checkEqu("124", list.strOf(1)); - checkEqu((int64_t) 111, list.tagOf(0)); - checkEqu((int64_t) 222, list.tagOf(1)); - checkEqu((int64_t) 300, list.tagOf(2)); + checkEqu((int64_t ) 111, list.tagOf(0)); + checkEqu((int64_t ) 222, list.tagOf(1)); + checkEqu((int64_t ) 300, list.tagOf(2)); - checkEqu((int64_t) 300, list.tagOf(2)); + checkEqu((int64_t ) 300, list.tagOf(2)); list.replaceString(2, "4"); checkEqu("4", list.strOf(2)); - checkEqu((int64_t) 111, list.tagOf(0)); - checkEqu((int64_t) 222, list.tagOf(1)); - checkEqu((int64_t) 300, list.tagOf(2)); + checkEqu((int64_t ) 111, list.tagOf(0)); + checkEqu((int64_t ) 222, list.tagOf(1)); + checkEqu((int64_t ) 300, list.tagOf(2)); list.replaceTag(2, 123); checkEqu("4", list.strOf(2)); - checkEqu((int64_t) 111, list.tagOf(0)); - checkEqu((int64_t) 222, list.tagOf(1)); - checkEqu((int64_t) 123, list.tagOf(2)); + checkEqu((int64_t ) 111, list.tagOf(0)); + checkEqu((int64_t ) 222, list.tagOf(1)); + checkEqu((int64_t ) 123, list.tagOf(2)); } - void testEqu(){ + void testEqu() { ReStringList list1; ReStringList list2; @@ -126,7 +127,7 @@ private: checkF(list1.equal(list2)); checkF(list2.equal(list1)); } - void testJoin(){ + void testJoin() { ReStringList list; const char* str = "1;abc;xyz;4;;99"; list.split(str, ';'); @@ -146,8 +147,8 @@ private: list.join(";", value, true); checkEqu("xxx1;2", value); } - void testFile(){ - if (true){ + void testFile() { + if (true) { ReByteBuffer file; buildFilename("abc.csv", file); @@ -177,8 +178,8 @@ private: } //log(false, "end of testFile()"); } - void testBase(){ - if (true){ + void testBase() { + if (true) { ReStringList list; ReByteBuffer value; @@ -191,17 +192,17 @@ private: int index = 0; checkEqu("123", list.strOf(index)); checkEqu(4U, list.sizeOf(index)); - checkEqu((int64_t) 100, list.tagOf(index)); + checkEqu((int64_t ) 100, list.tagOf(index)); index++; checkEqu("a", list.strOf(index)); checkEqu(2U, list.sizeOf(index)); - checkEqu((int64_t) 200, list.tagOf(index)); + checkEqu((int64_t ) 200, list.tagOf(index)); index++; checkEqu("vwxyz", list.strOf(index)); checkEqu(6U, list.sizeOf(index)); - checkEqu((int64_t) 300, list.tagOf(index)); + checkEqu((int64_t ) 300, list.tagOf(index)); checkEqu(12U, list.sumOfSizes()); @@ -212,22 +213,22 @@ private: index = 0; checkEqu("0", list.strOf(index)); checkEqu(2U, list.sizeOf(index)); - checkEqu((int64_t) 50, list.tagOf(index)); + checkEqu((int64_t ) 50, list.tagOf(index)); index++; checkEqu("123", list.strOf(index)); checkEqu(4U, list.sizeOf(index)); - checkEqu((int64_t) 100, list.tagOf(index)); + checkEqu((int64_t ) 100, list.tagOf(index)); index++; checkEqu("a", list.strOf(index)); checkEqu(2U, list.sizeOf(index)); - checkEqu((int64_t) 200, list.tagOf(index)); + checkEqu((int64_t ) 200, list.tagOf(index)); index++; checkEqu("vwxyz", list.strOf(index)); checkEqu(6U, list.sizeOf(index)); - checkEqu((int64_t) 300, list.tagOf(index)); + checkEqu((int64_t ) 300, list.tagOf(index)); checkEqu(0U, list.indexOf("0")); checkEqu(1U, list.indexOf("123")); @@ -245,10 +246,10 @@ private: checkEqu(3u, list.indexOf("vwxyz", false, 3)); checkEqu(3u, list.indexOf("VwXyz", true, 3)); - checkEqu((ReStringList::Index) -1, list.indexOf("A")); - checkEqu((ReStringList::Index) -1, list.indexOf("0123")); - checkEqu((ReStringList::Index) -1, list.indexOf("a", false, 3)); - checkEqu((ReStringList::Index) -1, list.indexOf("A", true, 3)); + checkEqu((ReStringList::Index ) -1, list.indexOf("A")); + checkEqu((ReStringList::Index ) -1, list.indexOf("0123")); + checkEqu((ReStringList::Index ) -1, list.indexOf("a", false, 3)); + checkEqu((ReStringList::Index ) -1, list.indexOf("A", true, 3)); checkEqu(0u, list.nextStartingWith(0, "0")); checkEqu(1u, list.nextStartingWith(0, "12")); @@ -256,12 +257,15 @@ private: checkEqu(2u, list.nextStartingWith(1, "a")); checkEqu(2u, list.nextStartingWith(2, "a")); checkEqu(2u, list.nextStartingWith(0, "A", true)); - checkEqu((ReStringList::Index) -1, list.nextStartingWith(2, "Ab", true)); - checkEqu((ReStringList::Index) -1, list.nextStartingWith(0, "b", true)); + checkEqu((ReStringList::Index ) -1, + list.nextStartingWith(2, "Ab", true)); + checkEqu((ReStringList::Index ) -1, + list.nextStartingWith(0, "b", true)); checkEqu(3u, list.nextStartingWith(0, "vwxy", false)); checkEqu(3u, list.nextStartingWith(0, "vwxy", true)); - checkEqu((ReStringList::Index) -1, list.nextStartingWith(0, "vWxY", false)); + checkEqu((ReStringList::Index ) -1, + list.nextStartingWith(0, "vWxY", false)); ReStringList list2; list2.append("a", 100); @@ -289,7 +293,7 @@ private: }; extern void testReStringList(void); -void testReStringList(void){ +void testReStringList(void) { TestReStringList unit; } diff --git a/cunit/cuReStringUtils.cpp b/cunit/cuReStringUtils.cpp index 22ab490..15cf8eb 100644 --- a/cunit/cuReStringUtils.cpp +++ b/cunit/cuReStringUtils.cpp @@ -8,29 +8,31 @@ */ #include "base/rebase.hpp" -class TestReStringUtils : public ReTestUnit { +class TestReStringUtils: public ReTestUnit { public: - TestReStringUtils() : ReTestUnit("ReStringUtils", __FILE__){ + TestReStringUtils() : + ReTestUnit("ReStringUtils", __FILE__) { run(); } private: - void run(){ + void run() { testLengthOfUnsigned(); testStrnicmp(); testIsInList(); testSplitPath(); } - void testLengthOfUnsigned(){ + void testLengthOfUnsigned() { unsigned int value; - checkEqu(3, (int) ReStringUtils::lengthOfUnsigned("123.4", -1, &value)); - checkEqu(123, (int) value); + checkEqu(3, + (int ) ReStringUtils::lengthOfUnsigned("123.4", -1, &value)); + checkEqu(123, (int ) value); value = 0x47112011; - checkEqu(0, (int)ReStringUtils::lengthOfUnsigned("", 0, &value)); - checkEqu(0x47112011, (int) value); - checkEqu(2, (int) ReStringUtils::lengthOfUnsigned("235", 2, &value)); - checkEqu(23, (int) value); + checkEqu(0, (int )ReStringUtils::lengthOfUnsigned("", 0, &value)); + checkEqu(0x47112011, (int ) value); + checkEqu(2, (int ) ReStringUtils::lengthOfUnsigned("235", 2, &value)); + checkEqu(23, (int ) value); } - void testStrnicmp(){ + void testStrnicmp() { checkT(ReStringUtils::strnicmp("abc", "abc", 3) == 0); checkT(ReStringUtils::strnicmp("abc", "ab", 3) > 0); checkT(ReStringUtils::strnicmp("ab", "abc", 3) < 0); @@ -52,7 +54,7 @@ private: checkT(ReStringUtils::strnicmp("abc", "ab", 99) > 0); checkT(ReStringUtils::strnicmp("ab", "abc", 99) < 0); } - void testIsInList(){ + void testIsInList() { checkT(ReStringUtils::isInList("abc", ";abc;def", true)); checkT(ReStringUtils::isInList("aBc", ";abc;def", true)); checkF(ReStringUtils::isInList("aBc", ";abc;def", false)); @@ -72,7 +74,7 @@ private: checkF(ReStringUtils::isInList("aBc", ";abc", false)); } - void testSplitPath(){ + void testSplitPath() { ReByteBuffer fullname, protocol, path, name, ext; const char* fn = "file:/etc/samba/smb.cnf"; @@ -199,6 +201,6 @@ private: }; extern void testReStringUtils(void); -void testReStringUtils(void){ +void testReStringUtils(void) { TestReStringUtils unit; } diff --git a/cunit/cuReTest.cpp b/cunit/cuReTest.cpp index ca3c12a..b510a5a 100644 --- a/cunit/cuReTest.cpp +++ b/cunit/cuReTest.cpp @@ -8,37 +8,38 @@ */ #include "base/rebase.hpp" -class TestTestUnit : public ReTestUnit { +class TestTestUnit: public ReTestUnit { public: - TestTestUnit() : ReTestUnit("TestTest", __FILE__){ + TestTestUnit() : + ReTestUnit("TestTest", __FILE__) { run(); } private: - void run(){ + void run() { testFileNameInTestDir(); testTimer(); testBasic(); testColMarker(); testEquFiles(); } - void testFileNameInTestDir(){ + void testFileNameInTestDir() { ReByteBuffer fn; const char* name = buildFilename("xyz.txt", fn); checkEqu(name, fn.str()); checkT(fn.endsWith("xyz.txt")); checkT(fn.startsWith(testDir())); } - void testTimer(){ + void testTimer() { int64_t start = timer(); // busy wait (clock() measures only busy times): time_t to = time(NULL) + 1; - while(time(NULL) <= to){ + while (time(NULL) <= to) { // do nothing } int duration = milliSecSince(start); checkT(duration >= 1000 && duration < 3000); } - void testBasic(){ + void testBasic() { checkT(true); checkF(false); checkN(NULL); @@ -62,11 +63,11 @@ private: checkFileExists("/etc!/passwd"); log(false, "end of 8 expected errors"); } - void testColMarker(){ + void testColMarker() { checkEqu("-^", colMarker(2)); checkEqu("^", colMarker(0)); } - void testEquFiles(){ + void testEquFiles() { ReByteBuffer fn1; buildFilename("x1.txt", fn1); ReByteBuffer fn2; @@ -81,6 +82,6 @@ private: }; extern void testReTestUnit(void); -void testReTestUnit(void){ +void testReTestUnit(void) { TestTestUnit unit; } diff --git a/cunit/cuReTraverser.cpp b/cunit/cuReTraverser.cpp index 799b54f..fd94366 100644 --- a/cunit/cuReTraverser.cpp +++ b/cunit/cuReTraverser.cpp @@ -12,102 +12,103 @@ static const char* s_empty[] = { NULL }; -class TestReTraverser : public ReTestUnit { +class TestReTraverser: public ReTestUnit { public: - TestReTraverser() : ReTestUnit("ReTraverser", __FILE__), - m_base(), - m_buffer(), - m_logger(ReLogger::globalLogger()) - { - m_base = testDir(); - m_base.append("traverser"); - _mkdir(m_base.str(), ALLPERMS); + TestReTraverser() : + ReTestUnit("ReTraverser", __FILE__), + m_base(), + m_buffer(), + m_logger(ReLogger::globalLogger()) { + m_base = testDir(); + m_base.append("traverser"); + _mkdir(m_base.str(), ALLPERMS); m_base.append(OS_SEPARATOR, -1); run(); ReDirectory::deleteTree(m_base.str(), true); } private: - ReByteBuffer m_base; + ReByteBuffer m_base; ReByteBuffer m_buffer; ReLogger* m_logger; private: - const char* makeDir(const char* relPath){ - m_buffer = m_base; - m_buffer.append(relPath); - m_buffer.replaceAll("/", 1, OS_SEPARATOR, -1); - _mkdir(m_buffer.str(), ALLPERMS); - struct stat info; - if (stat(m_buffer.str(), &info) != 0){ - logF(true, "cannot create dir %1$s", m_buffer.str()); - } - return m_buffer.str(); - } - void makeFile(const char* relPath){ - ReByteBuffer path(m_base); - path.append("/").append(relPath); - path.replaceAll("/", 1, OS_SEPARATOR, -1); - createFile(path.str(), relPath); - struct stat info; - if (stat(path.str(), &info) != 0){ - logF(true, "cannot create file %1$s", path.str()); - } - } - void initTree(){ - makeFile("1.txt"); - makeDir("dir1"); - makeDir("dir2"); - makeDir("dir1/dir1_1"); - makeDir("dir1/dir1_2"); - makeDir("dir1/dir1_2/dir1_2_1"); + const char* makeDir(const char* relPath) { + m_buffer = m_base; + m_buffer.append(relPath); + m_buffer.replaceAll("/", 1, OS_SEPARATOR, -1); + _mkdir(m_buffer.str(), ALLPERMS); + struct stat info; + if (stat(m_buffer.str(), &info) != 0) { + logF(true, "cannot create dir %1$s", m_buffer.str()); + } + return m_buffer.str(); + } + void makeFile(const char* relPath) { + ReByteBuffer path(m_base); + path.append("/").append(relPath); + path.replaceAll("/", 1, OS_SEPARATOR, -1); + createFile(path.str(), relPath); + struct stat info; + if (stat(path.str(), &info) != 0) { + logF(true, "cannot create file %1$s", path.str()); + } + } + void initTree() { + makeFile("1.txt"); + makeDir("dir1"); + makeDir("dir2"); + makeDir("dir1/dir1_1"); + makeDir("dir1/dir1_2"); + makeDir("dir1/dir1_2/dir1_2_1"); makeDir("dir1/cache"); - makeFile("dir1/dir1_2/dir1_2_1/x1.txt"); - makeFile("dir1/dir1_2/dir1_2_1/x2.txt"); - makeFile("dir2/2.x"); - makeFile("dir1/cache/cache.txt"); - } - void run(){ + makeFile("dir1/dir1_2/dir1_2_1/x1.txt"); + makeFile("dir1/dir1_2/dir1_2_1/x2.txt"); + makeFile("dir2/2.x"); + makeFile("dir1/cache/cache.txt"); + } + void run() { initTree(); testBasic(); - testList(); + testList(); } - void testList(){ - const char* argv[] = { "list", m_base.str(), NULL }; - ReDirList(m_logger).run(2, argv); - } - void testCopyFile(){ + void testList() { + const char* argv[] = { "list", m_base.str(), NULL }; + ReDirList(m_logger).run(2, argv); + } + void testCopyFile() { #if defined __linux__ - ReByteBuffer src(m_base); - src.append("dir1/dir1_2/dir1_2_1/x1.txt"); - ReByteBuffer trg(testDir()); - trg.append("copy_x1.txt"); - ReByteBuffer buffer; + ReByteBuffer src(m_base); + src.append("dir1/dir1_2/dir1_2_1/x1.txt"); + ReByteBuffer trg(testDir()); + trg.append("copy_x1.txt"); + ReByteBuffer buffer; buffer.ensureSize(5); - ReDirSync::copyFile(src.str(), NULL, trg.str(), buffer, + ReDirSync::copyFile(src.str(), NULL, trg.str(), buffer, ReLogger::globalLogger()); - checkFileEqu(src.str(), trg.str()); + checkFileEqu(src.str(), trg.str()); #else - log(false, "testCopyFile not implemented"); + log(false, "testCopyFile not implemented"); #endif - } + } - void checkRelDate(time_t absTime, int relTime){ - int diff = int(time(NULL) - relTime - absTime); - if (diff < 0) - diff = - diff; - checkT(diff < 2); - } + void checkRelDate(time_t absTime, int relTime) { + int diff = int(time(NULL) - relTime - absTime); + if (diff < 0) + diff = -diff; + checkT(diff < 2); + } - void checkOneFile(const char* node, const char* parent, const ReHashList& hash){ - ReByteBuffer path, expected; - checkT(hash.get(ReByteBuffer(node), path)); - expected.set(parent, -1); - if (! expected.endsWith(OS_SEPARATOR)) - expected.append(OS_SEPARATOR); - if (! path.endsWith(expected.str(), -1)) - checkT(false); - } - void testBasic(){ + void checkOneFile(const char* node, const char* parent, + const ReHashList& hash) { + ReByteBuffer path, expected; + checkT(hash.get(ReByteBuffer(node), path)); + expected.set(parent, -1); + if (!expected.endsWith(OS_SEPARATOR)) + expected.append(OS_SEPARATOR); + if (!path.endsWith(expected.str(), -1)) + checkT(false); + } + void testBasic() { ReTraverser traverser(m_base.str()); RePatternList patterns; // exclude */cache/* @@ -117,12 +118,10 @@ private: int level = 0; ReDirStatus_t* entry; ReHashList hash; - while( (entry = traverser.rawNextFile(level)) != NULL){ + while ((entry = traverser.rawNextFile(level)) != NULL) { hash.put(ReByteBuffer(entry->node(), -1), entry->m_path); - logF(false, "%d: %-12s %2d %s", - level, entry->node(), - int(entry->fileSize()), - entry->m_path.str()); + logF(false, "%d: %-12s %2d %s", level, entry->node(), + int(entry->fileSize()), entry->m_path.str()); } checkOneFile("x1.txt", "dir1_2_1", hash); checkOneFile("x2.txt", "dir1_2_1", hash); @@ -134,6 +133,6 @@ private: }; extern void testReTraverser(void); -void testReTraverser(void){ +void testReTraverser(void) { TestReTraverser unit; } diff --git a/cunit/cuReVarArgs.cpp b/cunit/cuReVarArgs.cpp index 64c1928..61f32cd 100644 --- a/cunit/cuReVarArgs.cpp +++ b/cunit/cuReVarArgs.cpp @@ -8,22 +8,20 @@ */ #include "base/rebase.hpp" -class TestReVarArgs : public ReTestUnit, public ReVarArgTrigger { +class TestReVarArgs: public ReTestUnit, public ReVarArgTrigger { public: - TestReVarArgs() - : - ReTestUnit("ReVarArgs", __FILE__), - m_argNo(0), - m_maxNo(0) - { + TestReVarArgs() : + ReTestUnit("ReVarArgs", __FILE__), + m_argNo(0), + m_maxNo(0) { run(); } - virtual void newArg(int no, int maxNo){ + virtual void newArg(int no, int maxNo) { m_argNo = no; m_maxNo = maxNo; } private: - void run(){ + void run() { ReVarArgs list("$1 $$ $2"); list.registerTrigger(this); @@ -32,12 +30,11 @@ private: checkEqu(m_maxNo, 2); checkEqu("0 $ 009", list.asCString()); - list.reset("x$1y$2"); list.arg(1.5); checkEqu(m_argNo, 1); checkEqu(m_maxNo, 2); - list.arg(2.45,"%7.3f"); + list.arg(2.45, "%7.3f"); checkEqu(m_argNo, 2); checkEqu(m_maxNo, 2); checkEqu("x1.500000y 2.450", list.asCString()); @@ -58,6 +55,6 @@ private: }; extern void testReVarArgs(void); -void testReVarArgs(void){ +void testReVarArgs(void) { TestReVarArgs unit; } diff --git a/cunit/cuReconfig.cpp b/cunit/cuReconfig.cpp index 5b54e21..f194bf5 100644 --- a/cunit/cuReconfig.cpp +++ b/cunit/cuReconfig.cpp @@ -8,20 +8,22 @@ */ #include "base/rebase.hpp" -class TestReConfigFile : public ReTestUnit { +class TestReConfigFile: public ReTestUnit { typedef ReHashList::Byte Byte; public: - TestReConfigFile() : ReTestUnit("ReConfigFile", __FILE__){ + TestReConfigFile() : + ReTestUnit("ReConfigFile", __FILE__) { run(); } private: - void run(){ + void run() { testBasic(); } - void testBasic(){ + void testBasic() { ReByteBuffer fn; buildFilename("reconfigfile.cfg", fn); - createFile(fn.str(), "#x.int=a\nx.int=1\nx.bool=true\nx.str=abc\nx.bool2=0\nstring=abc\n"); + createFile(fn.str(), + "#x.int=a\nx.int=1\nx.bool=true\nx.str=abc\nx.bool2=0\nstring=abc\n"); ReConfigFile config(fn.str()); checkT(config.isValid()); checkEqu(1, config.getInteger("x.int", 2)); @@ -44,6 +46,6 @@ private: }; extern void testReConfigFile(void); -void testReConfigFile(void){ +void testReConfigFile(void) { TestReConfigFile unit; } diff --git a/cunit/testall.cpp b/cunit/testall.cpp index f88d3d2..7e55440 100644 --- a/cunit/testall.cpp +++ b/cunit/testall.cpp @@ -14,7 +14,7 @@ static bool s_testAll = true; -void testBase(){ +void testBase() { extern void testReSeqArray(void); testReSeqArray(); @@ -42,7 +42,7 @@ void testBase(){ testReLogger(); } -void testString(){ +void testString() { void testReStringUtils(void); testReStringUtils(); @@ -57,35 +57,35 @@ void testString(){ extern void testReMatcher(); testReMatcher(); } -void testOs(){ +void testOs() { void testReDirTools(); testReDirTools(); - if (s_testAll){ + if (s_testAll) { void testReTraverser(); testReTraverser(); void testReDirTools(); testReDirTools(); } } -void testMath(){ +void testMath() { extern void testReMD5(); testReMD5(); extern void testReRandomizer(); testReRandomizer(); } -void testAll(){ - try - { +void testAll() { + try { testMath(); - if (s_testAll){ + if (s_testAll) { testBase(); testString(); testMath(); testOs(); } - } catch (ReException e){ - fprintf(stderr, "testBase.cpp: unexpected exception: %s\n", e.getMessage()); + } catch (ReException e) { + fprintf(stderr, "testBase.cpp: unexpected exception: %s\n", + e.getMessage()); } } diff --git a/math/ReMD5.cpp b/math/ReMD5.cpp index 4bc855b..fe9aea3 100644 --- a/math/ReMD5.cpp +++ b/math/ReMD5.cpp @@ -10,48 +10,39 @@ #define __LITTLE_ENDIAN__ -const int ReMD5::m_s[64] = { - 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, - 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, - 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, - 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 -}; +const int ReMD5::m_s[64] = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, + 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, + 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, + 21, 6, 10, 15, 21, 6, 10, 15, 21 }; static int s_ix = 0; // for x in [1..64] : int(2**32 * sin(x)) -const uint32_t ReMD5::m_K[64] = { - 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, - 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, - 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, - 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, - 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, - 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, - 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, - 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, - 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, - 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, - 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, - 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, - 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, - 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 -}; +const uint32_t ReMD5::m_K[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db, + 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, + 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, + 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, + 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, + 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, + 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, + 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, + 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, + 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, + 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, + 0xeb86d391 }; /** * Constructor. */ ReMD5::ReMD5() : - //m_digest - // m_hexDigest; - // m_waiting[64]; - m_lengthWaiting(0), - m_length(0), - m_a0(0x67452301), - m_b0(0xefcdab89), - m_c0(0x98badcfe), - m_d0(0x10325476), - m_finalized(false) -{ + //m_digest + // m_hexDigest; + // m_waiting[64]; + m_lengthWaiting(0), + m_length(0), + m_a0(0x67452301), + m_b0(0xefcdab89), + m_c0(0x98badcfe), + m_d0(0x10325476), + m_finalized(false) { } /** @@ -65,8 +56,8 @@ ReMD5::~ReMD5() { * * @return the binary digest (16 byte array) */ -const uint8_t* ReMD5::digest(){ - if (! m_finalized){ +const uint8_t* ReMD5::digest() { + if (!m_finalized) { finalize(); } return m_digest; @@ -81,7 +72,7 @@ const uint8_t* ReMD5::digest(){ * @param block the rest input (incomplete chunk) * @param blockLength the length of the block: 0..63 */ -void ReMD5::finalize(){ +void ReMD5::finalize() { uint8_t* block = m_waiting; int blockLength = m_lengthWaiting; // append "1" bit to message @@ -144,10 +135,10 @@ void ReMD5::finalize(){ * * @return the binary digest (16 byte array) */ -const ReByteBuffer& ReMD5::hexDigest(){ - if (m_hexDigest.length() == 0){ +const ReByteBuffer& ReMD5::hexDigest() { + if (m_hexDigest.length() == 0) { digest(); - for (int ix = 0; ix < 16; ix++){ + for (int ix = 0; ix < 16; ix++) { m_hexDigest.appendInt(m_digest[ix], "%02x"); } } @@ -159,12 +150,12 @@ const ReByteBuffer& ReMD5::hexDigest(){ * * This method is a direct programming of the algorithm described in wikipedia. */ -void ReMD5::processChunk2(const uint8_t block[64]){ +void ReMD5::processChunk2(const uint8_t block[64]) { uint32_t M[16]; // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 - for (int ix = 0; ix < 16; ix++){ + for (int ix = 0; ix < 16; ix++) { uint32_t x = block[3]; - for (int jj = 2; jj >= 0; jj--){ + for (int jj = 2; jj >= 0; jj--) { x = (x << 8) + block[jj]; } M[ix] = x; @@ -182,39 +173,39 @@ void ReMD5::processChunk2(const uint8_t block[64]){ #if defined TRACE_MD5 printf("neu: (%s)\n", block); #endif - for (int i = 0; i < 64; i++){ + for (int i = 0; i < 64; i++) { #if defined TRACE_MD5 if (i < 8) printf("%2d: A: %08x B: %08x C: %08x D%08x\n", i, A, B, C, D); #endif - if (i < 16){ + if (i < 16) { # define F1(B, C, D) ((B & C) | (~ B & D)) // F := (B and C) or ((not B) and D) F = F1(B, C, D); g = i; - } else if (i < 32){ + } else if (i < 32) { // F := (D and B) or (C and (not D)) // g := (5×i + 1) mod 16 # define F2(B, C, D) ((D & B) | (C & ~ D)) F = F2(B, C, D); - g = (5*i + 1) % 16; - } else if (i < 48){ + g = (5 * i + 1) % 16; + } else if (i < 48) { // F := B xor C xor D // g := (3×i + 5) mod 16 # define F3(B, C, D) ((B ^ C) ^ D) F = F3(B, C, D); - g = (3*i + 5) % 16; + g = (3 * i + 5) % 16; } else { // F := C xor (B or (not D)) # define F4(B, C, D) (C ^ (B | ~ D)) // g := (7×i) mod 16 F = F4(B, C, D); - g = (7*i) % 16; + g = (7 * i) % 16; } #if defined TRACE_MD5 if (i < 8) printf(" K[%2d]: %08x M[%2d]: %08x shift: %02d\n", - i, m_K[i], g, M[g], m_s[i]); + i, m_K[i], g, M[g], m_s[i]); #endif uint32_t dTemp = D; D = C; @@ -235,46 +226,46 @@ void ReMD5::processChunk2(const uint8_t block[64]){ */ #if defined OPTIMIZER_WORKS_GREAT inline void rotate_left_and_add(uint32_t& rc, uint32_t data, int shift, uint32_t term) { - rc = ((data << shift) | (data >> (32-shift))) + term; + rc = ((data << shift) | (data >> (32-shift))) + term; } -inline void X1(uint32_t &var, uint32_t x, uint32_t y, uint32_t z, - uint32_t data, uint32_t aConst, uint32_t shift) { +inline void X1(uint32_t &var, uint32_t x, uint32_t y, uint32_t z, + uint32_t data, uint32_t aConst, uint32_t shift) { //#define TRACE_MD5 #if defined TRACE_MD5 printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z); printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, aConst, data, shift); + s_ix - 1, aConst, data, shift); #endif rotate_left_and_add(var, var + F1(x, y, z) + data + aConst, shift, x); } -inline void X2(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, - uint32_t data, uint32_t aConst, uint32_t shift) { +inline void X2(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, + uint32_t data, uint32_t aConst, uint32_t shift) { #if defined TRACE_MD5 printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z); printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, aConst, data, shift); + s_ix - 1, aConst, data, shift); #endif - rotate_left_and_add(var, var + F2(x, y, z) + data + aConst, shift, x); + rotate_left_and_add(var, var + F2(x, y, z) + data + aConst, shift, x); } -inline void X3(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, - uint32_t data, uint32_t aConst, uint32_t shift) { +inline void X3(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, + uint32_t data, uint32_t aConst, uint32_t shift) { #if defined TRACE_MD5 printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z); printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, aConst, data, shift); + s_ix - 1, aConst, data, shift); #endif - rotate_left_and_add(var, var + F3(x, y, z) + data + aConst, shift, x); + rotate_left_and_add(var, var + F3(x, y, z) + data + aConst, shift, x); } -inline void X4(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, - uint32_t data, uint32_t aConst, uint32_t shift) { +inline void X4(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, + uint32_t data, uint32_t aConst, uint32_t shift) { #if defined TRACE_MD5 printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z); printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, aConst, data, shift); + s_ix - 1, aConst, data, shift); #endif - rotate_left_and_add(var, var + F4(x, y, z) + data + aConst, shift, x); + rotate_left_and_add(var, var + F4(x, y, z) + data + aConst, shift, x); } #else #define rotate_left_and_add(var, data, shift, term) { \ @@ -329,18 +320,18 @@ inline void X4(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, * ... * */ -void ReMD5::processChunk(const uint8_t block[64]){ +void ReMD5::processChunk(const uint8_t block[64]) { uint32_t M[16]; // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 #ifdef __LITTLE_ENDIAN__ - for (int ix = 0; ix < 16; ix++){ + for (int ix = 0; ix < 16; ix++) { //memcpy(&M[ix], block + ix * 4, 4); - M[ix] = * (uint32_t*) (block + ix*4); + M[ix] = *(uint32_t*) (block + ix * 4); } #elif defined __BIG_ENDIAN__ - for (int ix = 0; ix < 16; ix++){ + for (int ix = 0; ix < 16; ix++) { uint32_t x = block[3]; - for (int jj = 2; jj >= 0; jj--){ + for (int jj = 2; jj >= 0; jj--) { x = (x << 8) + block[jj]; } M[ix] = x; @@ -359,16 +350,16 @@ void ReMD5::processChunk(const uint8_t block[64]){ #endif /* Round 1 */ - X1(A, B, C, D, M[ 0], 0xd76aa478, 7); - X1(D, A, B, C, M[ 1], 0xe8c7b756, 12); - X1(C, D, A, B, M[ 2], 0x242070db, 17); - X1(B, C, D, A, M[ 3], 0xc1bdceee, 22); - X1(A, B, C, D, M[ 4], 0xf57c0faf, 7); - X1(D, A, B, C, M[ 5], 0x4787c62a, 12); - X1(C, D, A, B, M[ 6], 0xa8304613, 17); - X1(B, C, D, A, M[ 7], 0xfd469501, 22); - X1(A, B, C, D, M[ 8], 0x698098d8, 7); - X1(D, A, B, C, M[ 9], 0x8b44f7af, 12); + X1(A, B, C, D, M[0], 0xd76aa478, 7); + X1(D, A, B, C, M[1], 0xe8c7b756, 12); + X1(C, D, A, B, M[2], 0x242070db, 17); + X1(B, C, D, A, M[3], 0xc1bdceee, 22); + X1(A, B, C, D, M[4], 0xf57c0faf, 7); + X1(D, A, B, C, M[5], 0x4787c62a, 12); + X1(C, D, A, B, M[6], 0xa8304613, 17); + X1(B, C, D, A, M[7], 0xfd469501, 22); + X1(A, B, C, D, M[8], 0x698098d8, 7); + X1(D, A, B, C, M[9], 0x8b44f7af, 12); X1(C, D, A, B, M[10], 0xffff5bb1, 17); X1(B, C, D, A, M[11], 0x895cd7be, 22); X1(A, B, C, D, M[12], 0x6b901122, 7); @@ -377,58 +368,58 @@ void ReMD5::processChunk(const uint8_t block[64]){ X1(B, C, D, A, M[15], 0x49b40821, 22); /* Round 2 */ - X2 (A, B, C, D, M[ 1], 0xf61e2562, 5); - X2 (D, A, B, C, M[ 6], 0xc040b340, 9); - X2 (C, D, A, B, M[11], 0x265e5a51, 14); - X2 (B, C, D, A, M[ 0], 0xe9b6c7aa, 20); - X2 (A, B, C, D, M[ 5], 0xd62f105d, 5); - X2 (D, A, B, C, M[10], 0x02441453, 9); - X2 (C, D, A, B, M[15], 0xd8a1e681, 14); - X2 (B, C, D, A, M[ 4], 0xe7d3fbc8, 20); - X2 (A, B, C, D, M[ 9], 0x21e1cde6, 5); - X2 (D, A, B, C, M[14], 0xc33707d6, 9); - X2 (C, D, A, B, M[ 3], 0xf4d50d87, 14); - X2 (B, C, D, A, M[ 8], 0x455a14ed, 20); - X2 (A, B, C, D, M[13], 0xa9e3e905, 5); - X2 (D, A, B, C, M[ 2], 0xfcefa3f8, 9); - X2 (C, D, A, B, M[ 7], 0x676f02d9, 14); - X2 (B, C, D, A, M[12], 0x8d2a4c8a, 20); + X2(A, B, C, D, M[1], 0xf61e2562, 5); + X2(D, A, B, C, M[6], 0xc040b340, 9); + X2(C, D, A, B, M[11], 0x265e5a51, 14); + X2(B, C, D, A, M[0], 0xe9b6c7aa, 20); + X2(A, B, C, D, M[5], 0xd62f105d, 5); + X2(D, A, B, C, M[10], 0x02441453, 9); + X2(C, D, A, B, M[15], 0xd8a1e681, 14); + X2(B, C, D, A, M[4], 0xe7d3fbc8, 20); + X2(A, B, C, D, M[9], 0x21e1cde6, 5); + X2(D, A, B, C, M[14], 0xc33707d6, 9); + X2(C, D, A, B, M[3], 0xf4d50d87, 14); + X2(B, C, D, A, M[8], 0x455a14ed, 20); + X2(A, B, C, D, M[13], 0xa9e3e905, 5); + X2(D, A, B, C, M[2], 0xfcefa3f8, 9); + X2(C, D, A, B, M[7], 0x676f02d9, 14); + X2(B, C, D, A, M[12], 0x8d2a4c8a, 20); /* Round 3 */ - X3 (A, B, C, D, M[ 5], 0xfffa3942, 4); - X3 (D, A, B, C, M[ 8], 0x8771f681, 11); - X3 (C, D, A, B, M[11], 0x6d9d6122, 16); - X3 (B, C, D, A, M[14], 0xfde5380c, 23); - X3 (A, B, C, D, M[ 1], 0xa4beea44, 4); - X3 (D, A, B, C, M[ 4], 0x4bdecfa9, 11); - X3 (C, D, A, B, M[ 7], 0xf6bb4b60, 16); - X3 (B, C, D, A, M[10], 0xbebfbc70, 23); - X3 (A, B, C, D, M[13], 0x289b7ec6, 4); - X3 (D, A, B, C, M[ 0], 0xeaa127fa, 11); - X3 (C, D, A, B, M[ 3], 0xd4ef3085, 16); - X3 (B, C, D, A, M[ 6], 0x04881d05, 23); - X3 (A, B, C, D, M[ 9], 0xd9d4d039, 4); - X3 (D, A, B, C, M[12], 0xe6db99e5, 11); - X3 (C, D, A, B, M[15], 0x1fa27cf8, 16); - X3 (B, C, D, A, M[ 2], 0xc4ac5665, 23); + X3(A, B, C, D, M[5], 0xfffa3942, 4); + X3(D, A, B, C, M[8], 0x8771f681, 11); + X3(C, D, A, B, M[11], 0x6d9d6122, 16); + X3(B, C, D, A, M[14], 0xfde5380c, 23); + X3(A, B, C, D, M[1], 0xa4beea44, 4); + X3(D, A, B, C, M[4], 0x4bdecfa9, 11); + X3(C, D, A, B, M[7], 0xf6bb4b60, 16); + X3(B, C, D, A, M[10], 0xbebfbc70, 23); + X3(A, B, C, D, M[13], 0x289b7ec6, 4); + X3(D, A, B, C, M[0], 0xeaa127fa, 11); + X3(C, D, A, B, M[3], 0xd4ef3085, 16); + X3(B, C, D, A, M[6], 0x04881d05, 23); + X3(A, B, C, D, M[9], 0xd9d4d039, 4); + X3(D, A, B, C, M[12], 0xe6db99e5, 11); + X3(C, D, A, B, M[15], 0x1fa27cf8, 16); + X3(B, C, D, A, M[2], 0xc4ac5665, 23); /* Round 4 */ - X4 (A, B, C, D, M[ 0], 0xf4292244, 6); - X4 (D, A, B, C, M[ 7], 0x432aff97, 10); - X4 (C, D, A, B, M[14], 0xab9423a7, 15); - X4 (B, C, D, A, M[ 5], 0xfc93a039, 21); - X4 (A, B, C, D, M[12], 0x655b59c3, 6); - X4 (D, A, B, C, M[ 3], 0x8f0ccc92, 10); - X4 (C, D, A, B, M[10], 0xffeff47d, 15); - X4 (B, C, D, A, M[ 1], 0x85845dd1, 21); - X4 (A, B, C, D, M[ 8], 0x6fa87e4f, 6); - X4 (D, A, B, C, M[15], 0xfe2ce6e0, 10); - X4 (C, D, A, B, M[ 6], 0xa3014314, 15); - X4 (B, C, D, A, M[13], 0x4e0811a1, 21); - X4 (A, B, C, D, M[ 4], 0xf7537e82, 6); - X4 (D, A, B, C, M[11], 0xbd3af235, 10); - X4 (C, D, A, B, M[ 2], 0x2ad7d2bb, 15); - X4 (B, C, D, A, M[ 9], 0xeb86d391, 21); + X4(A, B, C, D, M[0], 0xf4292244, 6); + X4(D, A, B, C, M[7], 0x432aff97, 10); + X4(C, D, A, B, M[14], 0xab9423a7, 15); + X4(B, C, D, A, M[5], 0xfc93a039, 21); + X4(A, B, C, D, M[12], 0x655b59c3, 6); + X4(D, A, B, C, M[3], 0x8f0ccc92, 10); + X4(C, D, A, B, M[10], 0xffeff47d, 15); + X4(B, C, D, A, M[1], 0x85845dd1, 21); + X4(A, B, C, D, M[8], 0x6fa87e4f, 6); + X4(D, A, B, C, M[15], 0xfe2ce6e0, 10); + X4(C, D, A, B, M[6], 0xa3014314, 15); + X4(B, C, D, A, M[13], 0x4e0811a1, 21); + X4(A, B, C, D, M[4], 0xf7537e82, 6); + X4(D, A, B, C, M[11], 0xbd3af235, 10); + X4(C, D, A, B, M[2], 0x2ad7d2bb, 15); + X4(B, C, D, A, M[9], 0xeb86d391, 21); //Add this chunk's hash to result so far: m_a0 += A; @@ -439,7 +430,7 @@ void ReMD5::processChunk(const uint8_t block[64]){ /** * Prepares the instance for a new checksum. */ -void ReMD5::reset(){ +void ReMD5::reset() { m_a0 = 0x67452301; m_b0 = 0xefcdab89; m_c0 = 0x98badcfe; @@ -457,12 +448,12 @@ void ReMD5::reset(){ * @param block a block which should be added to the digest * @param blockLength the length of block */ -void ReMD5::update(const uint8_t* block, int blockLength){ +void ReMD5::update(const uint8_t* block, int blockLength) { if (blockLength == -1) blockLength = strlen((const char*) block); // process the "waiting" input (incomplete chunk): m_length += blockLength; - if (m_lengthWaiting > 0){ + if (m_lengthWaiting > 0) { int rest = 64 - m_lengthWaiting; if (rest > blockLength) rest = blockLength; @@ -471,18 +462,18 @@ void ReMD5::update(const uint8_t* block, int blockLength){ block += rest; m_lengthWaiting += rest; // Is the chunk complete? - if (m_lengthWaiting == 64){ + if (m_lengthWaiting == 64) { processChunk(m_waiting); m_lengthWaiting = 0; } } // process full 512 bit chunks (64 byte blocks): - for (int ix = blockLength / 64; ix > 0; ix--){ + for (int ix = blockLength / 64; ix > 0; ix--) { processChunk(block); block += 64; } blockLength %= 64; - if (blockLength != 0){ + if (blockLength != 0) { assert(m_lengthWaiting == 0); memcpy(m_waiting, block, blockLength); m_lengthWaiting = blockLength; diff --git a/math/ReMD5.hpp b/math/ReMD5.hpp index e02bb35..d4b5e1a 100644 --- a/math/ReMD5.hpp +++ b/math/ReMD5.hpp @@ -33,7 +33,7 @@ private: ReByteBuffer m_hexDigest; // normally only the first chunk is used (64 byte), but while finalization // a 2nd chunk may be needed. - uint8_t m_waiting[64+64]; + uint8_t m_waiting[64 + 64]; int m_lengthWaiting; // total count of input bytes: uint32_t m_length; diff --git a/math/ReObfuscator.cpp b/math/ReObfuscator.cpp index 7ad39e6..d4b961d 100644 --- a/math/ReObfuscator.cpp +++ b/math/ReObfuscator.cpp @@ -16,13 +16,12 @@ * @param charSet Specifies the character set which will be en/decoded. */ ReObfuscator::ReObfuscator(ReRandomizer& rand, CharSet charSet) : - m_rand(rand), - m_charSet(charSet), - m_min(0), - m_max(0), - m_range(0) -{ - switch(charSet){ + m_rand(rand), + m_charSet(charSet), + m_min(0), + m_max(0), + m_range(0) { + switch (charSet) { case CHAR96: m_min = ' '; m_max = 127; @@ -52,10 +51,10 @@ ReObfuscator::~ReObfuscator() { * * @return The decoded character. */ -char ReObfuscator::decode(char cc) const{ +char ReObfuscator::decode(char cc) const { char rc; int src = (int) (unsigned char) cc; - switch(m_charSet){ + switch (m_charSet) { case CHAR96: case CHAR224: if (src < m_min || src > m_max) @@ -89,7 +88,7 @@ char ReObfuscator::decode(char cc) const{ * @return The buffer. */ char* ReObfuscator::decode(char* buffer, int bufferLength) const { - if(bufferLength == -1) + if (bufferLength == -1) bufferLength = strlen(buffer); for (int ii = 0; ii < bufferLength; ii++) buffer[ii] = decode(buffer[ii]); @@ -102,17 +101,18 @@ char* ReObfuscator::decode(char* buffer, int bufferLength) const { * * @return The encoded character. */ -char ReObfuscator::encode(char cc) const{ +char ReObfuscator::encode(char cc) const { char rc; int src = (int) (unsigned char) cc; - switch(m_charSet) - { + switch (m_charSet) { case CHAR96: case CHAR224: if (src < m_min || src > m_max) rc = cc; else - rc = char (((src - m_min) + m_rand.nextInt(0, m_range - 1)) % m_range + m_min); + rc = char( + ((src - m_min) + m_rand.nextInt(0, m_range - 1)) % m_range + + m_min); break; case CHAR256: rc = (char) (src + (src + m_rand.nextInt(0, m_range - 1) % m_range)); @@ -134,8 +134,8 @@ char ReObfuscator::encode(char cc) const{ * * @return The buffer. */ -char* ReObfuscator::encode(char* buffer, int bufferLength) const{ - if(bufferLength == -1) +char* ReObfuscator::encode(char* buffer, int bufferLength) const { + if (bufferLength == -1) bufferLength = strlen(buffer); for (int ii = 0; ii < bufferLength; ii++) buffer[ii] = encode(buffer[ii]); @@ -146,7 +146,7 @@ char* ReObfuscator::encode(char* buffer, int bufferLength) const{ * * @return The current character set. */ -ReObfuscator::CharSet ReObfuscator::getCharSet() const{ +ReObfuscator::CharSet ReObfuscator::getCharSet() const { return m_charSet; } @@ -154,7 +154,7 @@ ReObfuscator::CharSet ReObfuscator::getCharSet() const{ * * @return The random generator. */ -ReRandomizer& ReObfuscator::getRandomizer() const{ +ReRandomizer& ReObfuscator::getRandomizer() const { return m_rand; } @@ -162,28 +162,29 @@ ReRandomizer& ReObfuscator::getRandomizer() const{ * * @param newSet The character set to set. */ -void ReObfuscator::setCharSet(CharSet newSet){ +void ReObfuscator::setCharSet(CharSet newSet) { m_charSet = newSet; } -static void testOne(const char* src, int bufferLength, - ReObfuscator& obf, ReCongruentialGenerator& rand){ - char buffer[256+1]; - assert((size_t) bufferLength < sizeof buffer); +static void testOne(const char* src, int bufferLength, ReObfuscator& obf, + ReCongruentialGenerator& rand) { + char buffer[256 + 1]; + assert((size_t ) bufferLength < sizeof buffer); memcpy(buffer, src, bufferLength); buffer[bufferLength] = '\0'; rand.setSeed(0x4711); obf.encode(buffer, bufferLength); - char buffer2[256+1]; + char buffer2[256 + 1]; memcpy(buffer2, buffer, bufferLength); buffer2[bufferLength] = '\0'; rand.setSeed(0x4711); obf.decode(buffer2, bufferLength); if (_memcmp(buffer2, src, bufferLength) != 0) - printf("%3d:%s\n -> %s\n -> %s\n", (int) obf.getCharSet(), src, buffer, buffer2); + printf("%3d:%s\n -> %s\n -> %s\n", (int) obf.getCharSet(), src, buffer, + buffer2); } -static void testIt(const char* src, int bufferLength, - ReObfuscator& obf, ReCongruentialGenerator& rand){ +static void testIt(const char* src, int bufferLength, ReObfuscator& obf, + ReCongruentialGenerator& rand) { if (bufferLength == -1) bufferLength = strlen(src); obf.setCharSet(ReObfuscator::CHAR96); @@ -194,7 +195,7 @@ static void testIt(const char* src, int bufferLength, testOne(src, bufferLength, obf, rand); } -void testObfuscator(){ +void testObfuscator() { ReCongruentialGenerator rand; ReObfuscator obf(rand); diff --git a/math/ReRandomizer.cpp b/math/ReRandomizer.cpp index 0c55da9..c2e2a12 100644 --- a/math/ReRandomizer.cpp +++ b/math/ReRandomizer.cpp @@ -7,7 +7,6 @@ * The latest sources: https://github.com/republib */ - #include "base/rebase.hpp" #include "math/remath.hpp" @@ -15,8 +14,7 @@ static bool s_trace = false; /** * @brief Constructor. */ -ReRandomizer::ReRandomizer() -{ +ReRandomizer::ReRandomizer() { } /** * @brief Destructor. @@ -25,7 +23,7 @@ ReRandomizer::~ReRandomizer() { } #if defined __linux__ -inline int abs(int x) { return x < 0 ? -x : x; } +inline int abs(int x) {return x < 0 ? -x : x;} #endif /** * @brief Returns the next random character. @@ -34,8 +32,7 @@ inline int abs(int x) { return x < 0 ? -x : x; } * * @return The next random character. */ -char ReRandomizer::nextChar() -{ +char ReRandomizer::nextChar() { char rc = nextInt(' ', ' ' + CHARRANGE - 1); return rc; } @@ -45,26 +42,26 @@ char ReRandomizer::nextChar() * * @return a number which is not predictable */ -ReRandomizer::seed_t ReRandomizer::nearTrueRandom(){ +ReRandomizer::seed_t ReRandomizer::nearTrueRandom() { time_t random = time(NULL); static int dummy = 5; void* dummy2 = malloc(1); free(dummy2); - seed_t rc = (((seed_t) random) << 31) + ((seed_t) &dummy << 9) + (-random ^ 0x20111958) - ^ (seed_t(dummy2)); + seed_t rc = (((seed_t) random) << 31) + ((seed_t) &dummy << 9) + + (-random ^ 0x20111958) ^ (seed_t(dummy2)); #if defined __linux__ int fh = open("/dev/urandom", O_RDONLY); char buffer[sizeof (seed_t)]; size_t length = 0; if (read(fh, buffer, sizeof buffer) > 0) - rc ^= *(seed_t*) buffer; + rc ^= *(seed_t*) buffer; close(fh); #elif defined __WIN32__ #else #error "no true random" #endif - return rc; + return rc; } /** * @brief Returns the next random integer. @@ -75,9 +72,9 @@ ReRandomizer::seed_t ReRandomizer::nearTrueRandom(){ * * @return The next seed. */ -int ReRandomizer::nextInt(int maxValue, int minValue){ +int ReRandomizer::nextInt(int maxValue, int minValue) { int rc; - if (minValue > maxValue){ + if (minValue > maxValue) { rc = minValue; minValue = maxValue; maxValue = rc; @@ -91,9 +88,9 @@ int ReRandomizer::nextInt(int maxValue, int minValue){ int64_t offset = seed % range; rc = (int) (minValue + offset); } - if (s_trace){ + if (s_trace) { static int count = 0; - printf ("%c %8x ", count++ % 4 == 0 ? '\n' : ' ', rc); + printf("%c %8x ", count++ % 4 == 0 ? '\n' : ' ', rc); } return rc; } @@ -107,9 +104,9 @@ int ReRandomizer::nextInt(int maxValue, int minValue){ * * @return The next seed. */ -int64_t ReRandomizer::nextInt64(int64_t maxValue, int64_t minValue){ +int64_t ReRandomizer::nextInt64(int64_t maxValue, int64_t minValue) { seed_t rc; - if (minValue > maxValue){ + if (minValue > maxValue) { rc = minValue; minValue = maxValue; maxValue = rc; @@ -124,12 +121,13 @@ int64_t ReRandomizer::nextInt64(int64_t maxValue, int64_t minValue){ rc = minValue + seed % (maxValue - minValue + 1); else { // int64 overflow: we need a higher precision: - double rc2 = (double) minValue + fmod((double) seed, (double) (maxValue - minValue)); + double rc2 = (double) minValue + + fmod((double) seed, (double) (maxValue - minValue)); rc = (int) rc2; } - if (s_trace){ + if (s_trace) { static int count = 0; - printf ("%c %16llx ", count++ % 4 == 0 ? '\n' : ' ', rc); + printf("%c %16llx ", count++ % 4 == 0 ? '\n' : ' ', rc); } return rc; } @@ -139,8 +137,8 @@ int64_t ReRandomizer::nextInt64(int64_t maxValue, int64_t minValue){ * * @return The next seed. */ -ReRandomizer::seed_t ReCongruentialGenerator::nextSeed(){ - m_seed = m_seed * m_factor + m_increment; +ReRandomizer::seed_t ReCongruentialGenerator::nextSeed() { + m_seed = m_seed * m_factor + m_increment; return m_seed; } @@ -155,11 +153,12 @@ ReRandomizer::seed_t ReCongruentialGenerator::nextSeed(){ * * @result The buffer. */ -const char* ReRandomizer::nextString(int minLength, int maxLength, ReByteBuffer &buffer){ +const char* ReRandomizer::nextString(int minLength, int maxLength, + ReByteBuffer &buffer) { int len = nextInt(maxLength, minLength); buffer.setLength(len); char* ptr = buffer.buffer(); - for (int ii = 0; ii < len; ii++){ + for (int ii = 0; ii < len; ii++) { ptr[ii] = nextChar(); } return buffer.str(); @@ -174,17 +173,16 @@ const char* ReRandomizer::nextString(int minLength, int maxLength, ReByteBuffer * @param length The length of the array. * @param elemSize The size of one element of the array. */ -void ReRandomizer::shuffle(void* array, size_t length, size_t elemSize){ +void ReRandomizer::shuffle(void* array, size_t length, size_t elemSize) { int ii; char* cptr; int* iptr; int count = length * 3 / 2; - switch(elemSize) - { + switch (elemSize) { case 1: cptr = (char*) array; - for (ii = 0; ii < count; ii++){ + for (ii = 0; ii < count; ii++) { int ix1 = length - nextInt(1, length); int ix2 = length - nextInt(1, length); char x = cptr[ix1]; @@ -194,7 +192,7 @@ void ReRandomizer::shuffle(void* array, size_t length, size_t elemSize){ break; case sizeof(int): iptr = (int*) array; - for (ii = 0; ii < count; ii++){ + for (ii = 0; ii < count; ii++) { int ix1 = length - nextInt(1, length); int ix2 = length - nextInt(1, length); int x = iptr[ix1]; @@ -202,12 +200,11 @@ void ReRandomizer::shuffle(void* array, size_t length, size_t elemSize){ iptr[ix2] = x; } break; - default: - { + default: { char buffer[0x10000]; assert(elemSize < sizeof buffer); iptr = (int*) array; - for (ii = 0; ii < count; ii++){ + for (ii = 0; ii < count; ii++) { int ix1 = length - nextInt(1, length); int ix2 = length - nextInt(1, length); char* p1 = ((char*) array) + ix1 * elemSize; @@ -224,16 +221,15 @@ void ReRandomizer::shuffle(void* array, size_t length, size_t elemSize){ * @brief Constructor. */ ReCongruentialGenerator::ReCongruentialGenerator() : - m_seed(0x4711), - m_factor(214013), - m_increment(2531011), - m_lastSetSeed(0x4711) -{ + m_seed(0x4711), + m_factor(214013), + m_increment(2531011), + m_lastSetSeed(0x4711) { } /** * @brief Destructor. */ -ReCongruentialGenerator::~ReCongruentialGenerator(){ +ReCongruentialGenerator::~ReCongruentialGenerator() { } /** @@ -241,9 +237,8 @@ ReCongruentialGenerator::~ReCongruentialGenerator(){ * * @return The current factor. */ -ReRandomizer::seed_t ReCongruentialGenerator::factor() const -{ - return m_factor; +ReRandomizer::seed_t ReCongruentialGenerator::factor() const { + return m_factor; } /** @@ -251,9 +246,8 @@ ReRandomizer::seed_t ReCongruentialGenerator::factor() const * * @return The current increment. */ -ReRandomizer::seed_t ReCongruentialGenerator::increment() const -{ - return m_increment; +ReRandomizer::seed_t ReCongruentialGenerator::increment() const { + return m_increment; } /** @@ -261,9 +255,8 @@ ReRandomizer::seed_t ReCongruentialGenerator::increment() const * * @return The current seed. */ -ReRandomizer::seed_t ReCongruentialGenerator::seed() const -{ - return m_seed; +ReRandomizer::seed_t ReCongruentialGenerator::seed() const { + return m_seed; } /** @@ -271,7 +264,7 @@ ReRandomizer::seed_t ReCongruentialGenerator::seed() const * * Note: The constructor does the first setSeed(). */ -void ReCongruentialGenerator::reset(){ +void ReCongruentialGenerator::reset() { m_seed = m_lastSetSeed; } @@ -280,9 +273,8 @@ void ReCongruentialGenerator::reset(){ * * @param factor The new factor. */ -void ReCongruentialGenerator::setFactor(seed_t factor) -{ - this->m_factor = factor; +void ReCongruentialGenerator::setFactor(seed_t factor) { + this->m_factor = factor; } /** @@ -290,23 +282,20 @@ void ReCongruentialGenerator::setFactor(seed_t factor) * * @param increment The new increment. */ -void ReCongruentialGenerator::setIncrement(seed_t increment) -{ - this->m_increment = increment; +void ReCongruentialGenerator::setIncrement(seed_t increment) { + this->m_increment = increment; } /** @brief Sets the current seed. * * @param seed The seed to set. */ -void ReCongruentialGenerator::setSeed(seed_t seed) -{ - m_seed = m_lastSetSeed = seed; - if (s_trace) - printf(" Seed: %llx ", seed); +void ReCongruentialGenerator::setSeed(seed_t seed) { + m_seed = m_lastSetSeed = seed; + if (s_trace) + printf(" Seed: %llx ", seed); } - /** @brief Returns the next 64 bit pseudo random number. * * A congruential generator produces good random in the most significant @@ -314,8 +303,8 @@ void ReCongruentialGenerator::setSeed(seed_t seed) * Then x % m returns better results. * * @return a pseudo random number -*/ -ReRandomizer::seed_t ReShiftRandom::nextSeed(){ + */ +ReRandomizer::seed_t ReShiftRandom::nextSeed() { seed_t rc = ReCongruentialGenerator::nextSeed(); rc = ((rc & 0x7fffffff) << 33) | ((rc >> 31) & 0x1ffffffffll); return rc; diff --git a/math/ReRandomizer.hpp b/math/ReRandomizer.hpp index fec9395..c336ee7 100644 --- a/math/ReRandomizer.hpp +++ b/math/ReRandomizer.hpp @@ -15,15 +15,18 @@ */ class ReRandomizer { public: - enum { START_RANGE = ' ', - CHARRANGE = 128 - START_RANGE }; + enum { + START_RANGE = ' ', + CHARRANGE = 128 - START_RANGE + }; typedef uint64_t seed_t; public: ReRandomizer(); virtual ~ReRandomizer(); public: virtual int nextInt(int maxValue = INT_MAX, int minValue = 0); - virtual int64_t nextInt64(int64_t maxValue = LLONG_MAX, int64_t minValue = 0); + virtual int64_t nextInt64(int64_t maxValue = LLONG_MAX, + int64_t minValue = 0); char nextChar(); const char* nextString(int minLength, int maxLength, ReByteBuffer& buffer); void shuffle(void* array, size_t length, size_t elemSize); @@ -34,7 +37,7 @@ protected: /** @brief Returns the next pseudo random number. * @return the next pseudo random number * */ - virtual seed_t nextSeed() = 0; + virtual seed_t nextSeed() = 0; public: seed_t nearTrueRandom(); }; @@ -45,18 +48,18 @@ public: * seed = (seed * factor + increment) % modulus * In this implementation modulus is 2**64. */ -class ReCongruentialGenerator : public ReRandomizer { +class ReCongruentialGenerator: public ReRandomizer { public: ReCongruentialGenerator(); virtual ~ReCongruentialGenerator(); public: - seed_t factor() const; - seed_t increment() const; - seed_t seed() const; + seed_t factor() const; + seed_t increment() const; + seed_t seed() const; virtual void reset(); - void setFactor(seed_t factor); - void setIncrement(seed_t increment); - void setSeed(seed_t m_seed); + void setFactor(seed_t factor); + void setIncrement(seed_t increment); + void setSeed(seed_t m_seed); protected: friend class ReShiftRandom; virtual seed_t nextSeed(); @@ -67,7 +70,7 @@ private: seed_t m_lastSetSeed; }; -class ReShiftRandom : public ReCongruentialGenerator { +class ReShiftRandom: public ReCongruentialGenerator { protected: virtual seed_t nextSeed(); }; diff --git a/math/md5.cpp b/math/md5.cpp deleted file mode 100644 index 7423820..0000000 --- a/math/md5.cpp +++ /dev/null @@ -1,388 +0,0 @@ -/* MD5 - converted to C++ class by Frank Thilo (thilo@unix-ag.org) - for bzflag (http://www.bzflag.org) - - based on: - - md5.h and md5.c - reference implemantion of RFC 1321 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -/* interface header */ -#include "math/md5.hpp" -#include "assert.h" - -/* system implementation headers */ -#include - - -// Constants for MD5Transform routine. -#define S11 7 -#define S12 12 -#define S13 17 -#define S14 22 -#define S21 5 -#define S22 9 -#define S23 14 -#define S24 20 -#define S31 4 -#define S32 11 -#define S33 16 -#define S34 23 -#define S41 6 -#define S42 10 -#define S43 15 -#define S44 21 - -/////////////////////////////////////////////// - -// F, G, H and I are basic MD5 functions. -inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { - return x&y | ~x&z; -} - -inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { - return x&z | y&~z; -} - -inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { - return x^y^z; -} - -inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { - return y ^ (x | ~z); -} - -// rotate_left rotates x left n bits. -inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { - return (x << n) | (x >> (32-n)); -} -static int s_ix = 0; -// 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) { -//#define TRACE_MD5 -#if defined TRACE_MD5 - printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, a, b, c, d); - printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, ac, x, s); -#endif - a = rotate_left(a+ F(b,c,d) + x + ac, s) + b; -} - -inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { -#if defined TRACE_MD5 - printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, a, b, c, d); - printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, ac, x, s); -#endif - a = rotate_left(a + G(b,c,d) + x + ac, s) + b; -} - -inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { -#if defined TRACE_MD5 - printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, a, b, c, d); - printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, ac, x, s); -#endif - a = rotate_left(a + H(b,c,d) + x + ac, s) + b; -} - -inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { -#if defined TRACE_MD5 - printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, a, b, c, d); - printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n", - s_ix - 1, ac, x, s); -#endif - a = rotate_left(a + I(b,c,d) + x + ac, s) + b; -} - -////////////////////////////////////////////// - -// default ctor, just initailize -MD5::MD5() -{ - init(); -} - -////////////////////////////////////////////// - -// nifty shortcut ctor, compute MD5 for string and finalize it right away -MD5::MD5(const std::string &text) -{ - init(); - update(text.c_str(), text.length()); - finalize(); -} - -////////////////////////////// - -void MD5::init() -{ - finalized=false; - - count[0] = 0; - count[1] = 0; - - // load magic initialization constants. - state[0] = 0x67452301; - state[1] = 0xefcdab89; - state[2] = 0x98badcfe; - state[3] = 0x10325476; -} - -////////////////////////////// - -// decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. -void MD5::decode(uint4 output[], const uint1 input[], size_type len) -{ - for (unsigned int i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) | - (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24); -} - -////////////////////////////// - -// encodes input (uint4) into output (unsigned char). Assumes len is -// a multiple of 4. -void MD5::encode(uint1 output[], const uint4 input[], size_type len) -{ - for (size_type i = 0, j = 0; j < len; i++, j += 4) { - output[j] = input[i] & 0xff; - output[j+1] = (input[i] >> 8) & 0xff; - output[j+2] = (input[i] >> 16) & 0xff; - output[j+3] = (input[i] >> 24) & 0xff; - } -} - -////////////////////////////// - -// apply MD5 algo on a block -void MD5::transform(const uint1 block[blocksize]) -{ - uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - decode (x, block, blocksize); - -#if defined TRACE_MD5 - printf("old: (%s)\n", block); -#endif - /* 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 (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 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - 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 (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 (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 (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 (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 (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 (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 (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[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - 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 (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - 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 (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 (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - 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 (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 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - // Zeroize sensitive information. - memset(x, 0, sizeof x); -} - -////////////////////////////// - -// MD5 block update operation. Continues an MD5 message-digest -// operation, processing another message block -void MD5::update(const unsigned char input[], size_type length) -{ - // compute number of bytes mod 64 - size_type index = count[0] / 8 % blocksize; - - // Update number of bits - if ((count[0] += (length << 3)) < (length << 3)) - count[1]++; - count[1] += (length >> 29); - - // number of bytes we need to fill in buffer - size_type firstpart = 64 - index; - - size_type i; - - // transform as many times as possible. - if (length >= firstpart) - { - // fill buffer first, transform - memcpy(&buffer[index], input, firstpart); - transform(buffer); - - // transform chunks of blocksize (64 bytes) - for (i = firstpart; i + blocksize <= length; i += blocksize) - transform(&input[i]); - - index = 0; - } - else - i = 0; - - // buffer remaining input - memcpy(&buffer[index], &input[i], length-i); -} - -////////////////////////////// - -// for convenience provide a verson with signed char -void MD5::update(const char input[], size_type length) -{ - update((const unsigned char*)input, length); -} - -////////////////////////////// - -// MD5 finalization. Ends an MD5 message-digest operation, writing the -// the message digest and zeroizing the context. -MD5& MD5::finalize() -{ - static unsigned char padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - if (!finalized) { - // Save number of bits - unsigned char bits[8]; - encode(bits, count, 8); - - // pad out to 56 mod 64. - size_type index = count[0] / 8 % 64; - size_type padLen = (index < 56) ? (56 - index) : (120 - index); - update(padding, padLen); - - // Append length (before padding) - update(bits, 8); - - // Store state in digest - encode(digest, state, 16); - - // Zeroize sensitive information. - memset(buffer, 0, sizeof buffer); - memset(count, 0, sizeof count); - - finalized=true; - } - - return *this; -} - -////////////////////////////// - -// return hex representation of digest as string -std::string MD5::hexdigest() const -{ - if (!finalized) - return ""; - - char buf[33]; - for (int i=0; i<16; i++) - sprintf(buf+i*2, "%02x", digest[i]); - buf[32]=0; - - return std::string(buf); -} - -////////////////////////////// - -std::ostream& operator<<(std::ostream& out, MD5 md5) -{ - assert(false); - return out << md5.hexdigest(); -} - -////////////////////////////// - -std::string md5(const std::string str) -{ - MD5 md5 = MD5(str); - - return md5.hexdigest(); -} diff --git a/math/md5.hpp b/math/md5.hpp deleted file mode 100644 index e6f3e4c..0000000 --- a/math/md5.hpp +++ /dev/null @@ -1,93 +0,0 @@ -/* MD5 - converted to C++ class by Frank Thilo (thilo@unix-ag.org) - for bzflag (http://www.bzflag.org) - - based on: - - md5.h and md5.c - reference implementation of RFC 1321 - - Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All -rights reserved. - -License to copy and use this software is granted provided that it -is identified as the "RSA Data Security, Inc. MD5 Message-Digest -Algorithm" in all material mentioning or referencing this software -or this function. - -License is also granted to make and use derivative works provided -that such works are identified as "derived from the RSA Data -Security, Inc. MD5 Message-Digest Algorithm" in all material -mentioning or referencing the derived work. - -RSA Data Security, Inc. makes no representations concerning either -the merchantability of this software or the suitability of this -software for any particular purpose. It is provided "as is" -without express or implied warranty of any kind. - -These notices must be retained in any copies of any part of this -documentation and/or software. - -*/ - -#ifndef BZF_MD5_H -#define BZF_MD5_H - -#include -#include - - -// a small class for calculating MD5 hashes of strings or byte arrays -// it is not meant to be fast or secure -// -// usage: 1) feed it blocks of uchars with update() -// 2) finalize() -// 3) get hexdigest() string -// or -// MD5(std::string).hexdigest() -// -// assumes that char is 8 bit and int is 32 bit -class MD5 -{ -public: - typedef unsigned int size_type; // must be 32bit - - MD5(); - MD5(const std::string& text); - void update(const unsigned char *buf, size_type length); - void update(const char *buf, size_type length); - MD5& finalize(); - std::string hexdigest() const; - friend std::ostream& operator<<(std::ostream&, MD5 md5); - -private: - void init(); - typedef unsigned char uint1; // 8bit - typedef unsigned int uint4; // 32bit - enum {blocksize = 64}; // VC6 won't eat a const static int here - - void transform(const uint1 block[blocksize]); - static void decode(uint4 output[], const uint1 input[], size_type len); - static void encode(uint1 output[], const uint4 input[], size_type len); - - bool finalized; - uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk - uint4 count[2]; // 64bit counter for number of bits (lo, hi) - uint4 state[4]; // digest so far - uint1 digest[16]; // the result - - // low level logic operations - 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 uint4 rotate_left(uint4 x, int n); - 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); -}; - -std::string md5(const std::string str); - -#endif diff --git a/os/ReDirTools.cpp b/os/ReDirTools.cpp index 06e94d9..5d2825e 100644 --- a/os/ReDirTools.cpp +++ b/os/ReDirTools.cpp @@ -28,22 +28,19 @@ enum LOCATION_DIRTOOL { const char* ReDirTools::m_version = "2015.02.25"; ReLogger* ReDirTools::m_logger = NULL; -static const char* s_helpSummary[] = { - "dirtool or dt ", +static const char* s_helpSummary[] = { "dirtool or dt ", " Useful commands around directory trees.", - " Type 'dirtool help ' for more help.", - ":", + " Type 'dirtool help ' for more help.", ":", "batch produce output to handle the found files with a script", "help shows info about the arguments/options", "list shows the meta data of the selected files", - "md5 shows the MD5 checksum of the selected files", + "md5 shows the MD5 checksum of the selected files", "statistic shows statistics about a direcctory tree", "synchronize copies only modified or new files from", " from a source directory tre to a target", - "touch sets the filetimes", - "which finds a file in a path list (like PATH)", - NULL -}; + "touch sets the filetimes", + "which finds a file in a path list (like PATH)", + NULL }; const char* s_batchUsage[] = { ": batch [] [ ...]", @@ -52,93 +49,76 @@ const char* s_batchUsage[] = { " each line starts (usually) with a script name (see -c)", " then it follows the full filename of the found file", " use --arguments or --script to configure the output line", - NULL -}; + NULL }; const char* s_batchExamples[] = { "dirtool batch -cbackup.bat --basename-pattern=;*.txt;*.doc e:\\data", "dirtool batch --type=r '--arguments=backup.sh !basename! !path!' usr etc", - NULL -}; + NULL }; const char* s_listUsage[] = { ": l(ist) [] [ ...]", " lists the metadata (size, modification date ...) of the selected files", - NULL -}; -const char* s_listExamples[] = { - "dirtool list --min-size=10M e:\\data", - "dirtool li --type=f -y7d --size=10M -p;*.cpp;*.hpp;Makefile*;-*~ /home/data", - NULL -}; + NULL }; +const char* s_listExamples[] = + { "dirtool list --min-size=10M e:\\data", + "dirtool li --type=f -y7d --size=10M -p;*.cpp;*.hpp;Makefile*;-*~ /home/data", + NULL }; const char* s_md5Usage[] = { ": m(d5) [] [ ...]", " shows the MD5 check sum of the given files", - NULL -}; -const char* s_md5Examples[] = { - "dirtool md5 --buffer-size=512 e:\\data", + NULL }; +const char* s_md5Examples[] = { "dirtool md5 --buffer-size=512 e:\\data", "dirtool m --type=f --size=10M -p;*.iso /home/iso /down/debian.iso", - NULL -}; - -static const char* s_statisticUsage[] = { - ": st(atistic) [] [ ...] []", - " shows a statistic about a directory tree", - " a directory path: relative or absolute", - " 0: only the summary of will be shown", - " 1: shows the summery of each subdir of and the total", - " n: shows the summery of each subdir until level and the total", - " default: 1", - ":", - NULL -}; -const char* s_statisticExamples[] = { - "dirtool st -q -t0 e:\\windows", - "dirtool statistic --quiet --kbyte --trace-interval=60 ../mail ../remember 2", - "dirtool stat -q --kbyte d:data 2", - NULL -}; - -const char* s_syncUsage[] = { - ": sy(nchronize) [ ...] ", - " Synchronizes the content of a directory tree with another.", - " Newer or missing files will be copied", - " If a source name ends with the separator (/ in linux, \\ in win) the target", - " will be completed with the basename of the source.", - " Example:", - " 'sync home backup' copies the file home/x.txt to backup/home/x.txt", - " 'sync data/ backup/data2' copies the file home/x.txt to backup/data2/x.txt", - NULL -}; + NULL }; + +static const char* s_statisticUsage[] = + { ": st(atistic) [] [ ...] []", + " shows a statistic about a directory tree", + " a directory path: relative or absolute", + " 0: only the summary of will be shown", + " 1: shows the summery of each subdir of and the total", + " n: shows the summery of each subdir until level and the total", + " default: 1", ":", + NULL }; +const char* s_statisticExamples[] = + { "dirtool st -q -t0 e:\\windows", + "dirtool statistic --quiet --kbyte --trace-interval=60 ../mail ../remember 2", + "dirtool stat -q --kbyte d:data 2", + NULL }; + +const char* s_syncUsage[] = + { ": sy(nchronize) [ ...] ", + " Synchronizes the content of a directory tree with another.", + " Newer or missing files will be copied", + " If a source name ends with the separator (/ in linux, \\ in win) the target", + " will be completed with the basename of the source.", " Example:", + " 'sync home backup' copies the file home/x.txt to backup/home/x.txt", + " 'sync data/ backup/data2' copies the file home/x.txt to backup/data2/x.txt", + NULL }; const char* s_syncExamples[] = { "dirtool sync --basename-pattern=;*.txt;*.doc e:\\data\\ d:\\backup\\data2", "dirtool sync --type=r --max-size=1G usr etc /media/backup", - NULL -}; + NULL }; -const char* s_touchUsage[] = { - ": touch [] [ ...]", - " sets the filetimes (modification and/or access time) of the selected files", - NULL -}; +const char* s_touchUsage[] = + { ": touch [] [ ...]", + " sets the filetimes (modification and/or access time) of the selected files", + NULL }; const char* s_touchExamples[] = { "dirtool touch -p;*.csv -m2014.12.1/8:12 e:\\data e:\\history\\readme.txt", - "dirtool touch -p;*.cpp --modified=now-4d12H /home/data" , - "dirtool touch -p;*.csv -m+1m . e:\\data e:\\history\\readme.txt", - NULL -}; + "dirtool touch -p;*.cpp --modified=now-4d12H /home/data", + "dirtool touch -p;*.csv -m+1m . e:\\data e:\\history\\readme.txt", + NULL }; const char* s_whichUsage[] = { ": w(hicht) [] [ ...]", " finds a file in a path list (like PATH)", - NULL -}; + NULL }; const char* s_whichExamples[] = { "dirtool which --list=JAVA_CLASSPATH org.jdom.jar *.jdom*.jar", "dirtool which find.exe", - NULL -}; + NULL }; /** * Constructor. * @@ -146,22 +126,21 @@ const char* s_whichExamples[] = { * @param example a string vector with some examples how to use the command */ ReDirOptions::ReDirOptions(const char* usage[], const char* examples[]) : - ReTraceUnit(INT_MAX, INT_MAX), - m_programArgs(usage, examples), - m_nodePatterns(), - m_pathPatterns(), - m_compoundUsage(NULL), - m_countCompoundUsage(0), - m_output(stdout), - m_verboseLevel(V_NORMAL) -{ + ReTraceUnit(INT_MAX, INT_MAX), + m_programArgs(usage, examples), + m_nodePatterns(), + m_pathPatterns(), + m_compoundUsage(NULL), + m_countCompoundUsage(0), + m_output(stdout), + m_verboseLevel(V_NORMAL) { m_nodePatterns.setIgnoreCase(true); m_pathPatterns.setIgnoreCase(true); } /** * Destructor. */ -ReDirOptions::~ReDirOptions(){ +ReDirOptions::~ReDirOptions() { close(); delete[] m_compoundUsage; } @@ -169,95 +148,95 @@ ReDirOptions::~ReDirOptions(){ * Adds a usage component to the compound usage message list. * @param usage a string vector containing a part of the usage message */ -void ReDirOptions::addCompoundUsage(const char** usage){ - int start = 0; - while(m_compoundUsage[start] != NULL){ - if (++start >= m_countCompoundUsage) - assert(false); - } - for (int ix = 0; usage[ix] != NULL; ix++){ - if (start + ix > m_countCompoundUsage){ - assert(false); - break; - } - m_compoundUsage[start + ix] = usage[ix]; - } +void ReDirOptions::addCompoundUsage(const char** usage) { + int start = 0; + while (m_compoundUsage[start] != NULL) { + if (++start >= m_countCompoundUsage) + assert(false); + } + for (int ix = 0; usage[ix] != NULL; ix++) { + if (start + ix > m_countCompoundUsage) { + assert(false); + break; + } + m_compoundUsage[start + ix] = usage[ix]; + } } /** * Adds the standard filter options. */ -void ReDirOptions::addStandardFilterOptions(){ +void ReDirOptions::addStandardFilterOptions() { // standard short options: D d O o P p T t v y Z z - m_programArgs.addInt("maxdepth", - i18n("the depth of the subdirectory is lower or equal \n" - "0: search is done only in the base directory"), - 'D', "max-depth", 512); - m_programArgs.addInt("mindepth", - i18n("the depth of the subdirectory is greater or equal \n" - "0: search is done in all subdirectories"), - 'd', "min-depth", 0); - m_programArgs.addString("output", - i18n("the name of the output file.\n" - "The output will written to this file instead of stdout"), - 'O', "output-file", false, NULL); - m_programArgs.addString("older", - i18n("the modification date is older than \n" - " is a date (e.g. 2015.02.17) or number followed by an unit\n" - "units: m(inutes) h(hours), d(days). Default: m(inutes)\n" - "examples: -o25 --older-than=30d -o24h -o2009.3.2/12:00 -o1999.01.01"), - 'o', "older-than", false, NULL); - m_programArgs.addString("pathpattern", - i18n("a list of patterns for the path (without basename)\n" - "the separator is the first character of the list\n" - "Each pattern can contain '*' as wildcard\n" - "If the first character is '-' the pattern is a 'not pattern':\n" - "A directory will be entered if at least one of the positive patterns\n" - "and none of the 'not patterns' matches\n" - "examples:\n" - "';music;pic*' enters music and xy/Music and PIC and pictures but not xy/pic and img\n" - "';*;-.git;.hg' ignores .git and xy/z/.git and .ht"), - 'P', "path-pattern", false, NULL); - m_programArgs.addString("nodepattern", - i18n("a list of patterns for the basename (name without path) separated by ';'\n" - "Each pattern can contain '*' as wildcard\n" - "If the first character is '-' the pattern is a 'not pattern':\n" - "A file will be found if at least one of the positive patterns and none\n" - "of the 'not patterns' matches\n" - "examples: '*.cpp;*.hpp;Make*' '*;-*.bak;-*~"), - 'p', "basename-pattern", false, NULL); - m_programArgs.addString("verbose", - i18n("verbose level: 0: no info, 1: summary only, 2: normal, 3: chatter mode, 4: debug"), - 'v', "verbose", false, "1"); - m_programArgs.addInt("trace", - i18n("all seconds the current path will be traced\n" - "0: no trace"), - 'T', "trace-interval", 0); - m_programArgs.addString("type", - i18n("the file type\n" - " is a list of values:\n" - ": b(lock) c(har) d(irectory) (l)i(nkdir) l(ink) o(ther)\n" - " p(ipe) s(ocket) r(egular)\n" - "-sets: S(pecial)=bcspo N(ondir)=Slr\n" - "examples: -td --type=dr -tNi"), - 't', "type", false, NULL); - m_programArgs.addString("younger", - i18n("the modification date is younger than \n" - " is a date (e.g. 2015.02.17) or number followed by an unit\n" - "units: m(inutes) h(hours), d(days). Default: m(inutes)"), - 'y', "younger-than", false, NULL); - m_programArgs.addString("maxsize", - i18n("the filesize is greater or equal \n" - " is a number followed by an unit\n" - "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n" - "examples: -Z50m --max-size=1G"), - 'Z', "max-size", false, NULL); - m_programArgs.addString("minsize", - i18n("the filesize is greater or equal \n" - " is a number followed by an unit\n" - "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n" - "examples: -z50m --min-size=1G"), - 'z', "min-size", false, NULL); + m_programArgs.addInt("maxdepth", + i18n("the depth of the subdirectory is lower or equal \n" + "0: search is done only in the base directory"), 'D', "max-depth", + 512); + m_programArgs.addInt("mindepth", + i18n("the depth of the subdirectory is greater or equal \n" + "0: search is done in all subdirectories"), 'd', "min-depth", 0); + m_programArgs.addString("output", i18n("the name of the output file.\n" + "The output will written to this file instead of stdout"), 'O', + "output-file", false, NULL); + m_programArgs.addString("older", + i18n( + "the modification date is older than \n" + " is a date (e.g. 2015.02.17) or number followed by an unit\n" + "units: m(inutes) h(hours), d(days). Default: m(inutes)\n" + "examples: -o25 --older-than=30d -o24h -o2009.3.2/12:00 -o1999.01.01"), + 'o', "older-than", false, NULL); + m_programArgs.addString("pathpattern", + i18n( + "a list of patterns for the path (without basename)\n" + "the separator is the first character of the list\n" + "Each pattern can contain '*' as wildcard\n" + "If the first character is '-' the pattern is a 'not pattern':\n" + "A directory will be entered if at least one of the positive patterns\n" + "and none of the 'not patterns' matches\n" + "examples:\n" + "';music;pic*' enters music and xy/Music and PIC and pictures but not xy/pic and img\n" + "';*;-.git;.hg' ignores .git and xy/z/.git and .ht"), 'P', + "path-pattern", false, NULL); + m_programArgs.addString("nodepattern", + i18n( + "a list of patterns for the basename (name without path) separated by ';'\n" + "Each pattern can contain '*' as wildcard\n" + "If the first character is '-' the pattern is a 'not pattern':\n" + "A file will be found if at least one of the positive patterns and none\n" + "of the 'not patterns' matches\n" + "examples: '*.cpp;*.hpp;Make*' '*;-*.bak;-*~"), 'p', + "basename-pattern", false, NULL); + m_programArgs.addString("verbose", + i18n( + "verbose level: 0: no info, 1: summary only, 2: normal, 3: chatter mode, 4: debug"), + 'v', "verbose", false, "1"); + m_programArgs.addInt("trace", + i18n("all seconds the current path will be traced\n" + "0: no trace"), 'T', "trace-interval", 0); + m_programArgs.addString("type", i18n("the file type\n" + " is a list of values:\n" + ": b(lock) c(har) d(irectory) (l)i(nkdir) l(ink) o(ther)\n" + " p(ipe) s(ocket) r(egular)\n" + "-sets: S(pecial)=bcspo N(ondir)=Slr\n" + "examples: -td --type=dr -tNi"), 't', "type", false, NULL); + m_programArgs.addString("younger", + i18n( + "the modification date is younger than \n" + " is a date (e.g. 2015.02.17) or number followed by an unit\n" + "units: m(inutes) h(hours), d(days). Default: m(inutes)"), 'y', + "younger-than", false, NULL); + m_programArgs.addString("maxsize", + i18n( + "the filesize is greater or equal \n" + " is a number followed by an unit\n" + "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n" + "examples: -Z50m --max-size=1G"), 'Z', "max-size", false, NULL); + m_programArgs.addString("minsize", + i18n( + "the filesize is greater or equal \n" + " is a number followed by an unit\n" + "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n" + "examples: -z50m --min-size=1G"), 'z', "min-size", false, NULL); } /** @@ -270,103 +249,108 @@ void ReDirOptions::addStandardFilterOptions(){ * @return the value converted into the absolute (or relative) time * @throws ReOptionExecption */ -ReFileTime_t ReDirOptions::checkDate(const char* value){ - ReByteBuffer theValue(value, -1); +ReFileTime_t ReDirOptions::checkDate(const char* value) { + ReByteBuffer theValue(value, -1); time_t rcTime; - if (theValue.count(".") == 2){ - // a date: - int year, month, day; - int hour = 0; - int minute = 0; + if (theValue.count(".") == 2) { + // a date: + int year, month, day; + int hour = 0; + int minute = 0; int sec = 0; - switch (sscanf(value, "%d.%d.%d/%d:%d:%d", &year, &month, &day, &hour, &minute, &sec)){ - case 3: - case 4: + switch (sscanf(value, "%d.%d.%d/%d:%d:%d", &year, &month, &day, &hour, + &minute, &sec)) { + case 3: + case 4: case 5: - case 6: - { - if (year < 1980) - throw ReOptionException(&m_programArgs, - i18n("date < 1980.01.01: $1"), value); - struct tm time; - memset(&time, 0, sizeof time); - time.tm_year = year - 1900; - time.tm_mon = month - 1; - time.tm_mday = day; - time.tm_hour = hour; - time.tm_min = minute; + case 6: { + if (year < 1980) + throw ReOptionException(&m_programArgs, + i18n("date < 1980.01.01: $1"), value); + struct tm time; + memset(&time, 0, sizeof time); + time.tm_year = year - 1900; + time.tm_mon = month - 1; + time.tm_mday = day; + time.tm_hour = hour; + time.tm_min = minute; time.tm_sec = sec; - rcTime = mktime(&time); - break; - } - default: - throw ReOptionException(&m_programArgs, - i18n("invalid date/date-time value: $1 yyyy.mm.dd/hh:MM expected"), value); - } - } else if (theValue.count(":") >= 1){ - // a time: - int hour = 0; - int minute = 0; + rcTime = mktime(&time); + break; + } + default: + throw ReOptionException(&m_programArgs, + i18n( + "invalid date/date-time value: $1 yyyy.mm.dd/hh:MM expected"), + value); + } + } else if (theValue.count(":") >= 1) { + // a time: + int hour = 0; + int minute = 0; int sec = 0; - switch (sscanf(value, "%d:%d:%d", &hour, &minute, &sec)){ - case 2: - case 3: - { + switch (sscanf(value, "%d:%d:%d", &hour, &minute, &sec)) { + case 2: + case 3: { // the time (today) - rcTime = time(NULL) / 86400 * 86400 + hour * 3600 + minute * 60 + sec; - break; - } - default: - throw ReOptionException(&m_programArgs, - i18n("invalid time value: $1. HH:MM:SS expected"), value); - } - } else { - // a time distance value: - char unit = 'm'; - int count = 0; + rcTime = time(NULL) / 86400 * 86400 + hour * 3600 + minute * 60 + + sec; + break; + } + default: + throw ReOptionException(&m_programArgs, + i18n("invalid time value: $1. HH:MM:SS expected"), value); + } + } else { + // a time distance value: + char unit = 'm'; + int count = 0; int negativeFactor = 1; bool fromNow = theValue.startsWith("now"); - if (fromNow){ + if (fromNow) { theValue.remove(0, 3); } char cc = theValue.at(0); - if (cc == '-' || cc == '+'){ + if (cc == '-' || cc == '+') { if (cc == '-') negativeFactor = -1; theValue.remove(0, 1); } - switch(sscanf(theValue.str(), "%d%c", &count, &unit)){ - case 1: - case 2: - switch(unit){ + switch (sscanf(theValue.str(), "%d%c", &count, &unit)) { + case 1: + case 2: + switch (unit) { case 's': break; - case 'm': - count *= 60; - break; - case 'h': - count *= 60*60; - break; - case 'd': - count *= 24*60*60; - break; - default: - throw ReOptionException(&m_programArgs, - i18n("invalid unit $1. expected: s(econds) m(inutes) h(ours) d(ays)"), value); - } - rcTime = count * negativeFactor; - break; - default: - throw ReOptionException(&m_programArgs, - i18n("invalid relative time value $1 ( expected). : s m h d"), - value); - } - if (fromNow) + case 'm': + count *= 60; + break; + case 'h': + count *= 60 * 60; + break; + case 'd': + count *= 24 * 60 * 60; + break; + default: + throw ReOptionException(&m_programArgs, + i18n( + "invalid unit $1. expected: s(econds) m(inutes) h(ours) d(ays)"), + value); + } + rcTime = count * negativeFactor; + break; + default: + throw ReOptionException(&m_programArgs, + i18n( + "invalid relative time value $1 ( expected). : s m h d"), + value); + } + if (fromNow) rcTime += time(NULL); - } - ReFileTime_t rc; + } + ReFileTime_t rc; ReDirStatus_t::timeToFiletime(rcTime, rc); - return rc; + return rc; } /** * Checks whether the given value is a time expression. @@ -378,45 +362,45 @@ ReFileTime_t ReDirOptions::checkDate(const char* value){ * @return the value (multiplied with the unit factor) * @throws ReOptionExecption */ -time_t ReDirOptions::checkSize(const char* value){ - int64_t rc = 0; - char unit = 'b'; - switch (sscanf(value, "%lld%c", (long long int*) &rc, &unit)){ - case 1: - case 2: - switch(unit){ - case 'b': - break; - case 'k': - rc *= 1000; - break; - case 'K': - rc *= 1024; - break; - case 'm': - rc *= 1000*1000; - break; - case 'M': - rc *= 1024*1024; - break; - case 'g': - rc *= 1000LL*1000*1000; - break; - case 'G': - rc *= 1024LL*1024*1024; - break; - default: - throw ReOptionException(&m_programArgs, - i18n("invalid : $1. Expected: b k K m M g G"), - value); - } - break; - default: - throw ReOptionException(&m_programArgs, - i18n("invalid size value: $1 expected: : b k K m M g G"), - value); - } - return rc; +time_t ReDirOptions::checkSize(const char* value) { + int64_t rc = 0; + char unit = 'b'; + switch (sscanf(value, "%lld%c", (long long int*) &rc, &unit)) { + case 1: + case 2: + switch (unit) { + case 'b': + break; + case 'k': + rc *= 1000; + break; + case 'K': + rc *= 1024; + break; + case 'm': + rc *= 1000 * 1000; + break; + case 'M': + rc *= 1024 * 1024; + break; + case 'g': + rc *= 1000LL * 1000 * 1000; + break; + case 'G': + rc *= 1024LL * 1024 * 1024; + break; + default: + throw ReOptionException(&m_programArgs, + i18n("invalid : $1. Expected: b k K m M g G"), value); + } + break; + default: + throw ReOptionException(&m_programArgs, + i18n( + "invalid size value: $1 expected: : b k K m M g G"), + value); + } + return rc; } /** * Checks whether the given value is a valid pattern list. @@ -427,16 +411,16 @@ time_t ReDirOptions::checkSize(const char* value){ * @return the value (for chaining) * @throws ReOptionExecption */ -const char* ReDirOptions::checkPatternList(const char* value){ - if (isalnum(*value) || *value == '_' || *value == '*' - || *value == '.' || *value == '-') - throw ReOptionException(&m_programArgs, - i18n("invalid separator (first character): $1 use ';' instead"), - value); +const char* ReDirOptions::checkPatternList(const char* value) { + if (isalnum(*value) || *value == '_' || *value == '*' || *value == '.' + || *value == '-') + throw ReOptionException(&m_programArgs, + i18n("invalid separator (first character): $1 use ';' instead"), + value); if (strchr(value, OS_SEPARATOR_CHAR) != NULL) - throw ReOptionException(&m_programArgs, - i18n("slash not allowed in pattern list: $1"), value); - return value; + throw ReOptionException(&m_programArgs, + i18n("slash not allowed in pattern list: $1"), value); + return value; } /** * Checks whether the given value is a valid filetype list. @@ -445,56 +429,55 @@ const char* ReDirOptions::checkPatternList(const char* value){ * @return the bitmask * @throws ReOptionExecption */ -ReDirStatus_t::Type_t ReDirOptions::checkType(const char* value){ - int rc = ReDirStatus_t::TF_UNDEF; - while (*value != '\0'){ - switch(*value){ - case 'b': - rc |= ReDirStatus_t::TF_BLOCK; - break; - case 'c': - rc |= ReDirStatus_t::TF_CHAR; - break; - case 'd': - rc |= ReDirStatus_t::TF_SUBDIR; - break; - case 'i': - rc |= ReDirStatus_t::TF_LINK_DIR; - break; - case 'l': - rc |= ReDirStatus_t::TF_LINK; - break; - case 'o': - rc |= ReDirStatus_t::TF_OTHER; - break; - case 'p': - rc |= ReDirStatus_t::TF_PIPE; - break; - case 's': - rc |= ReDirStatus_t::TF_SOCKET; - break; - case 'r': - rc |= ReDirStatus_t::TF_REGULAR; - break; - case 'S': - rc |= ReDirStatus_t::TC_SPECIAL; - break; - case 'N': - rc |= ReDirStatus_t::TC_NON_DIR; - break; - case ' ': - case ',': - break; - default: - throw ReOptionException(&m_programArgs, - i18n("invalid type: $1 Expected: b(lock) c(har) d(irectory)" - " (l)i(nkdir) l(ink) o(ther) p(ipe) s(ocket) r(egular)" - " S(pecial=bcspo) N(ondir=Slr)"), - value); - } - value++; - } - return (ReDirStatus_t::Type_t) rc; +ReDirStatus_t::Type_t ReDirOptions::checkType(const char* value) { + int rc = ReDirStatus_t::TF_UNDEF; + while (*value != '\0') { + switch (*value) { + case 'b': + rc |= ReDirStatus_t::TF_BLOCK; + break; + case 'c': + rc |= ReDirStatus_t::TF_CHAR; + break; + case 'd': + rc |= ReDirStatus_t::TF_SUBDIR; + break; + case 'i': + rc |= ReDirStatus_t::TF_LINK_DIR; + break; + case 'l': + rc |= ReDirStatus_t::TF_LINK; + break; + case 'o': + rc |= ReDirStatus_t::TF_OTHER; + break; + case 'p': + rc |= ReDirStatus_t::TF_PIPE; + break; + case 's': + rc |= ReDirStatus_t::TF_SOCKET; + break; + case 'r': + rc |= ReDirStatus_t::TF_REGULAR; + break; + case 'S': + rc |= ReDirStatus_t::TC_SPECIAL; + break; + case 'N': + rc |= ReDirStatus_t::TC_NON_DIR; + break; + case ' ': + case ',': + break; + default: + throw ReOptionException(&m_programArgs, + i18n("invalid type: $1 Expected: b(lock) c(har) d(irectory)" + " (l)i(nkdir) l(ink) o(ther) p(ipe) s(ocket) r(egular)" + " S(pecial=bcspo) N(ondir=Slr)"), value); + } + value++; + } + return (ReDirStatus_t::Type_t) rc; } /** @@ -504,14 +487,14 @@ ReDirStatus_t::Type_t ReDirOptions::checkType(const char* value){ * @param message2 an additional message */ -void ReDirOptions::help(const char* errorMessage, const char* message2) const{ - ReByteBuffer msg; - if (errorMessage != 0) - msg.append(errorMessage, -1); - if (message2 != NULL) - msg.append(message2, -1); - m_programArgs.help(msg.str(), false, stdout); - exit(1); +void ReDirOptions::help(const char* errorMessage, const char* message2) const { + ReByteBuffer msg; + if (errorMessage != 0) + msg.append(errorMessage, -1); + if (message2 != NULL) + msg.append(message2, -1); + m_programArgs.help(msg.str(), false, stdout); + exit(1); } /** @@ -519,26 +502,26 @@ void ReDirOptions::help(const char* errorMessage, const char* message2) const{ * * @throws */ -void ReDirOptions::checkStandardFilterOptions(){ - ReByteBuffer buffer; - if (m_programArgs.getString("older", buffer)[0] != '\0') - checkDate(buffer.str()); - if (m_programArgs.getString("younger", buffer)[0] != '\0') - checkDate(buffer.str()); - if (m_programArgs.getString("type", buffer)[0] != '\0') - checkType(buffer.str()); - if (m_programArgs.getString("maxsize", buffer)[0] != '\0') - checkSize(buffer.str()); - if (m_programArgs.getString("minsize", buffer)[0] != '\0') - checkSize(buffer.str()); - if (m_programArgs.getString("nodepattern", buffer)[0] != '\0') - checkPatternList(buffer.str()); - if (m_programArgs.getString("pathpattern", buffer)[0] != '\0') - checkPatternList(buffer.str()); - if (m_programArgs.getString("verbose", buffer)[0] != '\0'){ +void ReDirOptions::checkStandardFilterOptions() { + ReByteBuffer buffer; + if (m_programArgs.getString("older", buffer)[0] != '\0') + checkDate(buffer.str()); + if (m_programArgs.getString("younger", buffer)[0] != '\0') + checkDate(buffer.str()); + if (m_programArgs.getString("type", buffer)[0] != '\0') + checkType(buffer.str()); + if (m_programArgs.getString("maxsize", buffer)[0] != '\0') + checkSize(buffer.str()); + if (m_programArgs.getString("minsize", buffer)[0] != '\0') + checkSize(buffer.str()); + if (m_programArgs.getString("nodepattern", buffer)[0] != '\0') + checkPatternList(buffer.str()); + if (m_programArgs.getString("pathpattern", buffer)[0] != '\0') + checkPatternList(buffer.str()); + if (m_programArgs.getString("verbose", buffer)[0] != '\0') { unsigned level = V_NORMAL; if (ReStringUtils::lengthOfUnsigned(buffer.str(), -1, &level) - != buffer.length()) + != buffer.length()) help(i18n("verbose level is not a number (or '')"), buffer.str()); else m_verboseLevel = VerboseLevel(level); @@ -548,8 +531,8 @@ void ReDirOptions::checkStandardFilterOptions(){ /** * Frees the resources. */ -void ReDirOptions::close(){ - if (m_output != stdout && m_output != stderr){ +void ReDirOptions::close() { + if (m_output != stdout && m_output != stderr) { fclose(m_output); } m_output = stdout; @@ -560,12 +543,12 @@ void ReDirOptions::close(){ * * @param size the size of the array: size = (field1 + field2 + ...) * sizeof(const char*) */ -void ReDirOptions::initCompoundUsage(size_t size){ - delete[] m_compoundUsage; - int count = size / sizeof m_compoundUsage[0]; - m_compoundUsage = new const char*[count]; - memset(m_compoundUsage, 0, size); - m_countCompoundUsage = count; +void ReDirOptions::initCompoundUsage(size_t size) { + delete[] m_compoundUsage; + int count = size / sizeof m_compoundUsage[0]; + m_compoundUsage = new const char*[count]; + memset(m_compoundUsage, 0, size); + m_countCompoundUsage = count; } /** @@ -579,13 +562,13 @@ void ReDirOptions::initCompoundUsage(size_t size){ * * @param buffer the pattern list as string, e.g. ";*;-cache" */ -void ReDirOptions::optimizePathPattern(ReByteBuffer& buffer){ +void ReDirOptions::optimizePathPattern(ReByteBuffer& buffer) { ReStringList list; ReStringList rootList; list.split(buffer.str() + 1, buffer.str()[0]); buffer.replaceAll(OS_SEPARATOR, 1, "/", 1); ReByteBuffer item; - for (int ix = 0; ix < (int) list.count(); ix++){ + for (int ix = 0; ix < (int) list.count(); ix++) { item.set(list.strOf(ix), -1); if (item.endsWith("/*")) item.setLength(item.length() - 2); @@ -593,12 +576,12 @@ void ReDirOptions::optimizePathPattern(ReByteBuffer& buffer){ bool notAnchored = item.startsWith("*/") || item.startsWith("-*/"); item.replaceAll("/", 1, OS_SEPARATOR, 1); list.replace(ix, item.str()); - if (notAnchored){ + if (notAnchored) { item.remove(item.str()[0] == '-' ? 1 : 0, 2); rootList.append(item.str(), 0); } } - if (rootList.count() > 0){ + if (rootList.count() > 0) { list.append(rootList); } item.set(buffer.str(), 1); @@ -610,35 +593,35 @@ void ReDirOptions::optimizePathPattern(ReByteBuffer& buffer){ * * @param filter OUT: the filter to set */ -void ReDirOptions::setFilterFromProgramArgs(ReDirEntryFilter_t& filter){ - ReByteBuffer buffer; - if (m_programArgs.getString("younger", buffer)[0] != '\0') - filter.m_maxAge = checkDate(buffer.str()); - if (m_programArgs.getString("older", buffer)[0] != '\0') - filter.m_minAge = checkDate(buffer.str()); - if (m_programArgs.getString("maxsize", buffer)[0] != '\0') - filter.m_maxSize = checkSize(buffer.str()); - if (m_programArgs.getString("minsize", buffer)[0] != '\0') - filter.m_minSize = checkSize(buffer.str()); - if (m_programArgs.getString("type", buffer)[0] != '\0') - filter.m_types = checkType(buffer.str()); - filter.m_minDepth = m_programArgs.getInt("mindepth"); - filter.m_maxDepth = m_programArgs.getInt("maxdepth"); - if (m_programArgs.getString("nodepattern", buffer)[0] != '\0'){ - checkPatternList(buffer.str()); - m_nodePatterns.set(buffer.str()); - filter.m_nodePatterns = &m_nodePatterns; - } - if (m_programArgs.getString("pathpattern", buffer)[0] != '\0'){ - checkPatternList(buffer.str()); +void ReDirOptions::setFilterFromProgramArgs(ReDirEntryFilter_t& filter) { + ReByteBuffer buffer; + if (m_programArgs.getString("younger", buffer)[0] != '\0') + filter.m_maxAge = checkDate(buffer.str()); + if (m_programArgs.getString("older", buffer)[0] != '\0') + filter.m_minAge = checkDate(buffer.str()); + if (m_programArgs.getString("maxsize", buffer)[0] != '\0') + filter.m_maxSize = checkSize(buffer.str()); + if (m_programArgs.getString("minsize", buffer)[0] != '\0') + filter.m_minSize = checkSize(buffer.str()); + if (m_programArgs.getString("type", buffer)[0] != '\0') + filter.m_types = checkType(buffer.str()); + filter.m_minDepth = m_programArgs.getInt("mindepth"); + filter.m_maxDepth = m_programArgs.getInt("maxdepth"); + if (m_programArgs.getString("nodepattern", buffer)[0] != '\0') { + checkPatternList(buffer.str()); + m_nodePatterns.set(buffer.str()); + filter.m_nodePatterns = &m_nodePatterns; + } + if (m_programArgs.getString("pathpattern", buffer)[0] != '\0') { + checkPatternList(buffer.str()); optimizePathPattern(buffer); - m_pathPatterns.set(buffer.str()); - filter.m_pathPatterns = &m_pathPatterns; - } - if ( (m_interval = m_programArgs.getInt("trace")) != 0) + m_pathPatterns.set(buffer.str()); + filter.m_pathPatterns = &m_pathPatterns; + } + if ((m_interval = m_programArgs.getInt("trace")) != 0) m_triggerCount = 10; - if (m_programArgs.getString("output", buffer)[0] != '\0'){ - if ( (m_output = fopen(buffer.str(), "w")) == NULL){ + if (m_programArgs.getString("output", buffer)[0] != '\0') { + if ((m_output = fopen(buffer.str(), "w")) == NULL) { help("cannot open output file", buffer.str()); m_output = stdout; } @@ -658,27 +641,26 @@ void ReDirOptions::setFilterFromProgramArgs(ReDirEntryFilter_t& filter){ * directory will be added as argument * @param logger logger for error messages */ -ReTool::ReTool(const char* usage[], const char* example[], - int minArguments, int reservedFirst, int reservedLast, - bool addCurrentDirIfNoArguments, ReLogger* logger) : - ReDirOptions(usage, example), - ReDirTreeStatistic(), - m_minArguments(minArguments), - m_reservedFirst(reservedFirst), - m_reservedLast(reservedLast), - m_addCurrentDirIfNoArguments(addCurrentDirIfNoArguments), - m_hasStandardArgs(true), - m_traverser(NULL, this, logger), - m_filter(), - m_start(time(NULL)), - m_logger(logger) -{ +ReTool::ReTool(const char* usage[], const char* example[], int minArguments, + int reservedFirst, int reservedLast, bool addCurrentDirIfNoArguments, + ReLogger* logger) : + ReDirOptions(usage, example), + ReDirTreeStatistic(), + m_minArguments(minArguments), + m_reservedFirst(reservedFirst), + m_reservedLast(reservedLast), + m_addCurrentDirIfNoArguments(addCurrentDirIfNoArguments), + m_hasStandardArgs(true), + m_traverser(NULL, this, logger), + m_filter(), + m_start(time(NULL)), + m_logger(logger) { } /** * Destructor. */ -ReTool::~ReTool(){ +ReTool::~ReTool() { } /** @@ -689,12 +671,14 @@ ReTool::~ReTool(){ * @param currentFile message for the trace * @return true (for chaining) */ -bool ReTool::trace(const char* currentFile){ +bool ReTool::trace(const char* currentFile) { ReByteBuffer buffer(" "); int duration = int(time(NULL) - m_startTime); buffer.appendInt(duration / 60).appendInt(duration % 60, ":%02d: "); - buffer.appendInt(m_files).appendChar('/').appendInt(m_traverser.directories()).append(" dir(s)"); - buffer.appendInt(m_files).appendChar('/').appendInt(m_traverser.files()).append(" file(s)"); + buffer.appendInt(m_files).appendChar('/').appendInt( + m_traverser.directories()).append(" dir(s)"); + buffer.appendInt(m_files).appendChar('/').appendInt(m_traverser.files()) + .append(" file(s)"); buffer.append(currentFile); fputs(buffer.str(), stdout); return true; @@ -707,22 +691,22 @@ bool ReTool::trace(const char* currentFile){ * @param argv program arguments * @param minArguments the command needs at least so many non option arguments */ -void ReTool::run(int argc, const char** argv){ +void ReTool::run(int argc, const char** argv) { try { m_programArgs.init(argc, argv); if (m_programArgs.getArgCount() < m_minArguments) m_programArgs.help(i18n("too few arguments"), false, stdout); if (m_hasStandardArgs) - setFilterFromProgramArgs(m_filter); + setFilterFromProgramArgs(m_filter); doIt(); - if (m_output != stdout){ + if (m_output != stdout) { fclose(m_output); m_output = stdout; } - - } catch (ReOptionException& exc) { - m_programArgs.help(exc.getMessage(), false, stdout); - } + + } catch (ReOptionException& exc) { + m_programArgs.help(exc.getMessage(), false, stdout); + } } /** * Evaluates the non option arguments which are names of files or directories. @@ -731,19 +715,19 @@ void ReTool::run(int argc, const char** argv){ * or processTree(). * */ -void ReTool::processFileArguments(){ +void ReTool::processFileArguments() { int max = m_programArgs.getArgCount() - m_reservedLast; // Test whether the arguments are files or directories: ReByteBuffer arg; - for (int ii = m_reservedFirst; ii < max; ii++){ + for (int ii = m_reservedFirst; ii < max; ii++) { arg = m_programArgs.getArg(ii); - if (! exists(arg) != 0) + if (!exists(arg) != 0) m_programArgs.help( - ReByteBuffer(i18n("not a file or a directory: ")).append(arg).str(), - false, stderr); + ReByteBuffer(i18n("not a file or a directory: ")).append(arg) + .str(), false, stderr); } // process the files: - for (int ii = m_reservedFirst; ii < max; ii++){ + for (int ii = m_reservedFirst; ii < max; ii++) { const char* arg = m_programArgs.getArg(ii); if (S_ISDIR(m_statInfo.st_mode)) processTree(arg); @@ -758,7 +742,7 @@ void ReTool::processFileArguments(){ * * @param filename the name of the file */ -void ReTool::processSingleFile(const char* filename){ +void ReTool::processSingleFile(const char* filename) { ReByteBuffer protocol; ReByteBuffer path; ReByteBuffer name; @@ -776,18 +760,18 @@ void ReTool::processSingleFile(const char* filename){ m_traverser.setPropertiesFromFilter(&m_filter); ReDirStatus_t entry(m_logger); entry.m_path = protocol; - if (entry.findFirst()){ + if (entry.findFirst()) { do { #if defined __linux__ bool found = strcmp(entry.node(), name.str()) == 0; #elif defined __WIN32__ bool found = _stricmp(entry.node(), name.str()) == 0; #endif - if (found && m_filter.match(entry)){ + if (found && m_filter.match(entry)) { processFile(&entry); break; } - } while(entry.findNext()); + } while (entry.findNext()); } entry.freeEntry(); } @@ -799,13 +783,13 @@ void ReTool::processSingleFile(const char* filename){ * * @param directory the name of the directory */ -void ReTool::processTree(const char* directory){ +void ReTool::processTree(const char* directory) { m_traverser.changeBase(directory); m_traverser.setPropertiesFromFilter(&m_filter); ReDirStatus_t* entry; int level; - while( (entry = m_traverser.nextFile(level, &m_filter)) != NULL){ - if (entry->isDirectory()){ + while ((entry = m_traverser.nextFile(level, &m_filter)) != NULL) { + if (entry->isDirectory()) { processDir(entry); m_directories++; } else { @@ -822,7 +806,7 @@ void ReTool::processTree(const char* directory){ * * @param entry the properties of the file to process */ -void ReTool::processFile(ReDirStatus_t* entry){ +void ReTool::processFile(ReDirStatus_t* entry) { fprintf(m_output, "+++ ignored (not a directory): %s\n", entry->fullName()); } /** @@ -830,18 +814,22 @@ void ReTool::processFile(ReDirStatus_t* entry){ * * @param prefix NULL or a line prefix */ -void ReTool::printSummary(const char* prefix){ - if (m_verboseLevel >= V_SUMMARY){ +void ReTool::printSummary(const char* prefix) { + if (m_verboseLevel >= V_SUMMARY) { int duration = int(time(NULL) - m_start); ReByteBuffer line; ReByteBuffer line2; statisticAsString(line); - double rate = duration == 0 ? 0.0 : (m_files + m_directories) / duration; + double rate = + duration == 0 ? 0.0 : (m_files + m_directories) / duration; line.append(rate, " %.1f").append(i18n("/sec"), -1); m_traverser.statisticAsString(line2); - line2.appendChar(' ').appendTime(duration).append(" ", 1).append(i18n("sec")); - fprintf(m_output, "%s=== filtered: %s\n", prefix == NULL ? "" : prefix, line.str()); - fprintf(m_output, "%s=== total: %s\n", prefix == NULL ? "" : prefix, line2.str()); + line2.appendChar(' ').appendTime(duration).append(" ", 1).append( + i18n("sec")); + fprintf(m_output, "%s=== filtered: %s\n", prefix == NULL ? "" : prefix, + line.str()); + fprintf(m_output, "%s=== total: %s\n", prefix == NULL ? "" : prefix, + line2.str()); } } @@ -852,7 +840,7 @@ void ReTool::printSummary(const char* prefix){ * * @param entry the properties of the directory to process */ -void ReTool::processDir(ReDirStatus_t* entry){ +void ReTool::processDir(ReDirStatus_t* entry) { fprintf(m_output, "+++ ignored (not a file): %s\n", entry->fullName()); } @@ -860,9 +848,8 @@ void ReTool::processDir(ReDirStatus_t* entry){ * Constructor. */ ReDirStatisticData::ReDirStatisticData() : - ReDirTreeStatistic(), - m_path() -{ + ReDirTreeStatistic(), + m_path() { } /** * Copy constructor. @@ -870,8 +857,7 @@ ReDirStatisticData::ReDirStatisticData() : * @param source the source to copy */ ReDirStatisticData::ReDirStatisticData(const ReDirStatisticData& source) : - m_path(source.m_path) -{ + m_path(source.m_path) { } /** * Assignment operator. @@ -879,7 +865,8 @@ ReDirStatisticData::ReDirStatisticData(const ReDirStatisticData& source) : * @param source the source to copy * @return the instance itself */ -ReDirStatisticData& ReDirStatisticData::operator =(const ReDirStatisticData& source){ +ReDirStatisticData& ReDirStatisticData::operator =( + const ReDirStatisticData& source) { m_sizes = source.m_sizes; m_files = source.m_files; m_directories = source.m_directories; @@ -895,19 +882,18 @@ ReDirStatisticData& ReDirStatisticData::operator =(const ReDirStatisticData& sou * @param deltaBuffer increment if content buffer must be increased */ ReDirStatistic::ReDirStatistic(ReLogger* logger, int deltaList, int deltaBuffer) : - ReTool(s_statisticUsage, s_statisticExamples, 2, 0, 1, false, logger), - m_list(deltaList, deltaBuffer) -{ + ReTool(s_statisticUsage, s_statisticExamples, 2, 0, 1, false, logger), + m_list(deltaList, deltaBuffer) { // standard short options: D d O o P p T t v y Z z - m_programArgs.addBool("kbyte", - i18n("output format is ' ' (like unix 'du' command)"), - 'k', "kbyte", false); - addStandardFilterOptions(); + m_programArgs.addBool("kbyte", + i18n("output format is ' ' (like unix 'du' command)"), 'k', + "kbyte", false); + addStandardFilterOptions(); } /** * Destructor. */ -ReDirStatistic::~ReDirStatistic(){ +ReDirStatistic::~ReDirStatistic() { } /** @@ -916,7 +902,7 @@ ReDirStatistic::~ReDirStatistic(){ * @param source the other instance * @return the instance itself */ -ReDirStatisticData& ReDirStatisticData::add(const ReDirStatisticData& source){ +ReDirStatisticData& ReDirStatisticData::add(const ReDirStatisticData& source) { m_sizes += source.m_sizes; m_files += source.m_files; m_directories += source.m_directories; @@ -925,7 +911,7 @@ ReDirStatisticData& ReDirStatisticData::add(const ReDirStatisticData& source){ /** * Initializes the data of the instance. */ -void ReDirStatisticData::clear(){ +void ReDirStatisticData::clear() { ReDirTreeStatistic::clear(); m_path.setLength(0); } @@ -935,108 +921,110 @@ void ReDirStatisticData::clear(){ * @param logger logger for error handling */ ReDirBatch::ReDirBatch(ReLogger* logger) : - ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger), - m_arguments(), - m_script(), - m_isExe(false) -{ + ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger), + m_arguments(), + m_script(), + m_isExe(false) { // standard short options: D d O o P p T t v y Z z - m_programArgs.addString("first", - i18n("defines the first line of the output"), - '1', "first-line", true, + m_programArgs.addString("first", + i18n("defines the first line of the output"), + '1', "first-line", true, #if defined __linux__ - "#! /bin/sh" + "#! /bin/sh" #elif defined __WIN32__ - "rem this batch is created by dirtool" + "rem this batch is created by dirtool" #endif - ); - m_programArgs.addString("arguments", - i18n("template for the output line.\n" - "Possible placeholders: (e.g. e:\\data\\sample.txt)\n" - " !full!: e:\\data\\sample.txt\n" - " !path!: e:\\data\\\n" - " !basename!: sample.txt\n" - " !name!: sample\n" - " !ext!: .txt\n" - "example: --arguments='echo !basename! in !path! found'"), - 'a', "arguments", false, NULL); - m_programArgs.addString("script", - i18n("name of the script (starts each output line)"), - 'c', "script", false, NULL); + ); + m_programArgs.addString("arguments", i18n("template for the output line.\n" + "Possible placeholders: (e.g. e:\\data\\sample.txt)\n" + " !full!: e:\\data\\sample.txt\n" + " !path!: e:\\data\\\n" + " !basename!: sample.txt\n" + " !name!: sample\n" + " !ext!: .txt\n" + "example: --arguments='echo !basename! in !path! found'"), 'a', + "arguments", false, NULL); + m_programArgs.addString("script", + i18n("name of the script (starts each output line)"), 'c', "script", + false, NULL); #if defined __WIN32__ - m_programArgs.addBool("isexe", - i18n("supresses the starting 'call' of each output line" - "neccessary if a *.exe will be called (instead of a *.bat)"), - 'x', "is-exe", false); + m_programArgs.addBool("isexe", + i18n("supresses the starting 'call' of each output line" + "neccessary if a *.exe will be called (instead of a *.bat)"), + 'x', "is-exe", false); #endif - addStandardFilterOptions(); -} - -static void replaceMakros(const char* arguments, ReDirStatus_t* entry, const char* delim, ReByteBuffer& line){ - line.set(arguments, -1); - // we prepare the removal of unwanted delimiters in constructed placeholders: - // example: !path!!name!: without correction: "e:\\data\\""xxx" - // We want: "e:\\data\\xxx" - line.replaceAll("!!", 2, "!\x01!", 3); - ReByteBuffer replacement; - if (strstr(arguments, "!full!") != NULL){ - replacement.set(delim, -1).append(entry->m_path); - replacement.append(entry->node(), -1).append(delim, -1); - line.replaceAll("!full!", 6, replacement.str(), replacement.length()); - } - if (strstr(arguments, "!path!") != NULL){ - replacement.set(delim, -1).append(entry->m_path).append(delim, -1); - line.replaceAll("!path!", 6, replacement.str(), replacement.length()); - } - if (strstr(arguments, "!basename!") != NULL){ - replacement.set(delim, -1).append(entry->node(), -1).append(delim, -1); - line.replaceAll("!basename!", 10, replacement.str(), replacement.length()); - } - if (strstr(arguments, "!name!") != NULL){ - replacement.set(delim, -1).append(entry->node(), -1); - int ix = replacement.rindexOf(".", 1); - if (ix > 1) - replacement.setLength(ix); - replacement.append(delim, -1); - line.replaceAll("!name!", 6, replacement.str(), replacement.length()); - } - if (strstr(arguments, "!ext!") != NULL){ - replacement.set(delim, -1).append(entry->node(), -1); - int ix = replacement.rindexOf(".", 1); - if (ix > 1) - replacement.remove(1, ix - 1); - else - replacement.setLength(1); - replacement.append(delim, -1); - line.replaceAll("!ext!", 5, replacement.str(), replacement.length()); - } - // We remove the unwanted delimiters (see above): - ReByteBuffer buffer; - buffer.set(delim, -1).appendChar('\01').append(delim, -1); - line.replaceAll(buffer.str(), buffer.length(), "", 0); + addStandardFilterOptions(); +} + +static void replaceMakros(const char* arguments, ReDirStatus_t* entry, + const char* delim, ReByteBuffer& line) { + line.set(arguments, -1); + // we prepare the removal of unwanted delimiters in constructed placeholders: + // example: !path!!name!: without correction: "e:\\data\\""xxx" + // We want: "e:\\data\\xxx" + line.replaceAll("!!", 2, "!\x01!", 3); + ReByteBuffer replacement; + if (strstr(arguments, "!full!") != NULL) { + replacement.set(delim, -1).append(entry->m_path); + replacement.append(entry->node(), -1).append(delim, -1); + line.replaceAll("!full!", 6, replacement.str(), replacement.length()); + } + if (strstr(arguments, "!path!") != NULL) { + replacement.set(delim, -1).append(entry->m_path).append(delim, -1); + line.replaceAll("!path!", 6, replacement.str(), replacement.length()); + } + if (strstr(arguments, "!basename!") != NULL) { + replacement.set(delim, -1).append(entry->node(), -1).append(delim, -1); + line.replaceAll("!basename!", 10, replacement.str(), + replacement.length()); + } + if (strstr(arguments, "!name!") != NULL) { + replacement.set(delim, -1).append(entry->node(), -1); + int ix = replacement.rindexOf(".", 1); + if (ix > 1) + replacement.setLength(ix); + replacement.append(delim, -1); + line.replaceAll("!name!", 6, replacement.str(), replacement.length()); + } + if (strstr(arguments, "!ext!") != NULL) { + replacement.set(delim, -1).append(entry->node(), -1); + int ix = replacement.rindexOf(".", 1); + if (ix > 1) + replacement.remove(1, ix - 1); + else + replacement.setLength(1); + replacement.append(delim, -1); + line.replaceAll("!ext!", 5, replacement.str(), replacement.length()); + } + // We remove the unwanted delimiters (see above): + ReByteBuffer buffer; + buffer.set(delim, -1).appendChar('\01').append(delim, -1); + line.replaceAll(buffer.str(), buffer.length(), "", 0); } /** * Creates the batch file. */ -void ReDirBatch::doIt(){ +void ReDirBatch::doIt() { ReByteBuffer buffer; m_programArgs.getString("arguments", m_arguments); m_programArgs.getString("script", m_script); if (m_arguments.length() + m_script.length() == 0) - help(i18n("one of the option must be set: -a (--arguments) or -c (--script)")); + help( + i18n( + "one of the option must be set: -a (--arguments) or -c (--script)")); #if defined __WIN32__ m_isExe = m_programArgs.getBool("isexe"); #endif m_programArgs.getString("first", buffer); - if (buffer.length() > 0) - fprintf(m_output, "%s\n", buffer.str()); + if (buffer.length() > 0) + fprintf(m_output, "%s\n", buffer.str()); processFileArguments(); #if defined __linux__ static const char* prefix = "# "; #elif defined __WIN32__ static const char* prefix = "rem "; #endif - printSummary(prefix); + printSummary (prefix); } /** @@ -1044,7 +1032,7 @@ void ReDirBatch::doIt(){ * * @param entry the properties of the directory to process */ -void ReDirBatch::processDir(ReDirStatus_t* entry){ +void ReDirBatch::processDir(ReDirStatus_t* entry) { processFile(entry); } @@ -1053,17 +1041,17 @@ void ReDirBatch::processDir(ReDirStatus_t* entry){ * * @param entry the properties of the file to process */ -void ReDirBatch::processFile(ReDirStatus_t* entry){ +void ReDirBatch::processFile(ReDirStatus_t* entry) { ReByteBuffer line; #if defined __linux__ - static const char* delim = "'"; + static const char* delim = "'"; #elif defined __WIN32__ static const char* delim = "\""; #endif - if (m_script.length() > 0){ + if (m_script.length() > 0) { #if defined __WIN32__ if (! m_isExe) - line.append("call "); + line.append("call "); #endif line.append(m_script).appendChar(' ').appendChar(delim[0]); line.append(entry->m_path).append(entry->node(), -1); @@ -1080,28 +1068,28 @@ void ReDirBatch::processFile(ReDirStatus_t* entry){ * @param logger logger for error handling */ ReDirList::ReDirList(ReLogger* logger) : - ReTool(s_listUsage, s_listExamples, 0, 0, 0, true, logger), - m_widthOwner(13), - m_shortFormat(false), - m_withRights(false), - m_numerical(false) -{ + ReTool(s_listUsage, s_listExamples, 0, 0, 0, true, logger), + m_widthOwner(13), + m_shortFormat(false), + m_withRights(false), + m_numerical(false) { // standard short options: D d O o P p T t v y Z z - m_programArgs.addBool("short", i18n("output is only path and basename"), - '1', "--short", false); - m_programArgs.addBool("rights", i18n("show the permission/right info"), - 'r', "--rights", false); - m_programArgs.addBool("numerical", i18n("the permission/right info is shown as numbers"), - 'n', "--numerical", false); - m_programArgs.addInt("owner", i18n("space reserved for owner/group"), - 'w', "--width-owner", 13); - addStandardFilterOptions(); + m_programArgs.addBool("short", i18n("output is only path and basename"), + '1', "--short", false); + m_programArgs.addBool("rights", i18n("show the permission/right info"), 'r', + "--rights", false); + m_programArgs.addBool("numerical", + i18n("the permission/right info is shown as numbers"), 'n', + "--numerical", false); + m_programArgs.addInt("owner", i18n("space reserved for owner/group"), 'w', + "--width-owner", 13); + addStandardFilterOptions(); } /** * Lists the metadata of the specified files. */ -void ReDirList::doIt(){ +void ReDirList::doIt() { m_shortFormat = m_programArgs.getBool("short"); m_withRights = m_programArgs.getBool("rights"); m_numerical = m_programArgs.getBool("numerical"); @@ -1115,7 +1103,7 @@ void ReDirList::doIt(){ * * @param entry the properties of the directory to process */ -void ReDirList::processDir(ReDirStatus_t* entry){ +void ReDirList::processDir(ReDirStatus_t* entry) { processFile(entry); } /** @@ -1123,7 +1111,7 @@ void ReDirList::processDir(ReDirStatus_t* entry){ * * @param entry the properties of the file to process */ -void ReDirList::processFile(ReDirStatus_t* entry){ +void ReDirList::processFile(ReDirStatus_t* entry) { ReByteBuffer bufferRights; ReByteBuffer bufferTime; if (m_shortFormat) @@ -1131,12 +1119,10 @@ void ReDirList::processFile(ReDirStatus_t* entry){ else { if (m_withRights) entry->rightsAsString(bufferRights, m_numerical, m_widthOwner); - fprintf(m_output, "%c%s %12.6f %s %s%s\n", - entry->typeAsChar(), - bufferRights.str(), - entry->fileSize() / 1E6, - entry->filetimeAsString(bufferTime), - entry->m_path.str(), entry->node()); + fprintf(m_output, "%c%s %12.6f %s %s%s\n", entry->typeAsChar(), + bufferRights.str(), entry->fileSize() / 1E6, + entry->filetimeAsString(bufferTime), entry->m_path.str(), + entry->node()); } } @@ -1146,19 +1132,19 @@ void ReDirList::processFile(ReDirStatus_t* entry){ * @param logger logger for error handling */ ReDirMD5::ReDirMD5(ReLogger* logger) : - ReTool(s_md5Usage, s_md5Examples, 0, 0, 0, true, logger), - m_buffer() -{ + ReTool(s_md5Usage, s_md5Examples, 0, 0, 0, true, logger), + m_buffer() { // standard short options: D d O o P p T t v y Z z - m_programArgs.addInt("buffersize", i18n("buffer size for file reading (in KiByte)"), - 'b', "--buffer-size", 4*1024); - addStandardFilterOptions(); + m_programArgs.addInt("buffersize", + i18n("buffer size for file reading (in KiByte)"), 'b', "--buffer-size", + 4 * 1024); + addStandardFilterOptions(); } /** * Lists the metadata of the specified files. */ -void ReDirMD5::doIt(){ +void ReDirMD5::doIt() { int size = m_programArgs.getInt("buffersize") * 1024; m_buffer.setLength(size); processFileArguments(); @@ -1170,14 +1156,14 @@ void ReDirMD5::doIt(){ * * @param entry the properties of the directory to process */ -void ReDirMD5::processDir(ReDirStatus_t* entry){ +void ReDirMD5::processDir(ReDirStatus_t* entry) { } /** * Processes one file. * * @param entry the properties of the file to process */ -void ReDirMD5::processFile(ReDirStatus_t* entry){ +void ReDirMD5::processFile(ReDirStatus_t* entry) { const char* name = entry->fullName(); FILE* fp = fopen(name, "rb"); if (fp != NULL) { @@ -1186,7 +1172,7 @@ void ReDirMD5::processFile(ReDirStatus_t* entry){ uint8_t* buffer = reinterpret_cast(m_buffer.buffer()); size_t blockSize = m_buffer.length(); - while( (readBytes = fread(buffer, 1, blockSize, fp)) > 0){ + while ((readBytes = fread(buffer, 1, blockSize, fp)) > 0) { digest.update(buffer, readBytes); } fclose(fp); @@ -1194,15 +1180,14 @@ void ReDirMD5::processFile(ReDirStatus_t* entry){ } } - /** * Calculates the statistic of a directory tree. * * */ const ReStringList& ReDirStatistic::calculate(const char* base, int level, - void (*formatter)(const ReDirStatisticData& data, ReDirStatistic& parent, - ReByteBuffer& line)){ + void (*formatter)(const ReDirStatisticData& data, ReDirStatistic& parent, + ReByteBuffer& line)) { ReDirEntryFilter_t filter; ReTraverser traverser(base, this); setFilterFromProgramArgs(filter); @@ -1211,7 +1196,7 @@ const ReStringList& ReDirStatistic::calculate(const char* base, int level, level = 1024; else if (level < 0) level = 0; - m_list.clear(); + m_list.clear(); ReDirStatisticData** dataStack = new ReDirStatisticData*[level + 1]; memset(dataStack, 0, sizeof dataStack[0] * (level + 1)); dataStack[0] = new ReDirStatisticData(); @@ -1222,27 +1207,29 @@ const ReStringList& ReDirStatistic::calculate(const char* base, int level, current->m_path.set(base, -1); ReByteBuffer line; bool useFilter = filter.m_minSize > 0 || filter.m_maxSize != -1 - || ! filetimeIsUndefined(filter.m_minAge) || ! filetimeIsUndefined(filter.m_maxAge) - || m_nodePatterns.count() > 0; - while( (entry = traverser.rawNextFile(currentDepth))){ - if (currentDepth <= level && ! entry->m_path.equals(current->m_path)){ - if (currentDepth <= topOfStack){ + || !filetimeIsUndefined(filter.m_minAge) + || !filetimeIsUndefined(filter.m_maxAge) || m_nodePatterns.count() > 0; + while ((entry = traverser.rawNextFile(currentDepth))) { + if (currentDepth <= level && !entry->m_path.equals(current->m_path)) { + if (currentDepth <= topOfStack) { // close the entries of the stack above the new top level: - while(topOfStack >= currentDepth){ + while (topOfStack >= currentDepth) { // Add the data to the parent: - if (topOfStack > 0) - dataStack[topOfStack - 1]->add(*dataStack[topOfStack]); - // Append it to the result: + if (topOfStack > 0) + dataStack[topOfStack - 1]->add(*dataStack[topOfStack]); + // Append it to the result: (*formatter)(*dataStack[topOfStack], *this, line); m_list.append(line); - topOfStack--; + topOfStack--; } - // We reuse the top of stack: - topOfStack++; - current = dataStack[topOfStack]; - // exchange the top of stack with the new found directory: - current->clear(); - current->m_path.set(entry->m_path.str(), entry->m_path.length());; + // We reuse the top of stack: + topOfStack++; + current = dataStack[topOfStack]; + // exchange the top of stack with the new found directory: + current->clear(); + current->m_path.set(entry->m_path.str(), + entry->m_path.length()); + ; } else { // set up a new stack entry: if (currentDepth != topOfStack + 1) @@ -1254,27 +1241,28 @@ const ReStringList& ReDirStatistic::calculate(const char* base, int level, else dataStack[topOfStack]->clear(); current = dataStack[topOfStack]; - current->m_path.set(entry->m_path.str(), entry->m_path.length()); + current->m_path.set(entry->m_path.str(), + entry->m_path.length()); } } - if (entry->isDirectory()){ + if (entry->isDirectory()) { current->m_directories++; - } else if (! useFilter || filter.match(*entry)){ + } else if (!useFilter || filter.match(*entry)) { current->m_sizes += entry->fileSize(); current->m_files++; } } - // close all dirs with parents: - while(topOfStack > 0){ + // close all dirs with parents: + while (topOfStack > 0) { // Add the data to the parent: dataStack[topOfStack - 1]->add(*dataStack[topOfStack]); // Append it to the result: (*formatter)(*dataStack[topOfStack], *this, line); m_list.append(line); - topOfStack--; + topOfStack--; } - // ... and the overall summery: - (*formatter)(*dataStack[0], *this, line); + // ... and the overall summery: + (*formatter)(*dataStack[0], *this, line); m_list.append(line); // free the resources: for (int ix = 0; ix <= level; ix++) @@ -1289,24 +1277,24 @@ const ReStringList& ReDirStatistic::calculate(const char* base, int level, * @param arc count of arguments in argv * @param argv the program arguments. */ -void ReDirStatistic::doIt(){ +void ReDirStatistic::doIt() { int depth = 1; - if (m_programArgs.getArgCount() > 1){ + if (m_programArgs.getArgCount() > 1) { const char* arg1 = m_programArgs.getArg(1); if (ReStringUtils::lengthOfUnsigned(arg1, -1, (unsigned *) &depth) == 0) m_programArgs.help("depth is not an integer", false, stdout); } - void (*proc) (const ReDirStatisticData& data, - ReDirStatistic& parent, ReByteBuffer& line) = &formatWithSizeFilesAndDirs; + void (*proc)(const ReDirStatisticData& data, ReDirStatistic& parent, + ReByteBuffer& line) = &formatWithSizeFilesAndDirs; if (m_programArgs.getBool("kbyte")) proc = &formatLikeDu; const ReStringList& list = calculate(m_programArgs.getArg(0), depth, proc); ReByteBuffer buffer; - for (size_t ix = 0; ix < list.count(); ix++){ + for (size_t ix = 0; ix < list.count(); ix++) { buffer.set(list.strOf(ix), list.strLengthOf(ix)); fprintf(m_output, "%s\n", buffer.str()); } - if (m_verboseLevel >= V_SUMMARY){ + if (m_verboseLevel >= V_SUMMARY) { int duration = int(time(NULL) - m_start); fprintf(m_output, "=== duration: "); if (duration >= 3600) @@ -1326,11 +1314,12 @@ void ReDirStatistic::doIt(){ * ReDirStatistic) * @param line OUT: the formatted line, the conclusion of the statistic data */ -void formatLikeDu(const ReDirStatisticData& data, - ReDirStatistic& parent, ReByteBuffer& line){ +void formatLikeDu(const ReDirStatisticData& data, ReDirStatistic& parent, + ReByteBuffer& line) { line.setLength(0); - // Round up to the next KiByte: - line.appendInt(int((data.m_sizes + 1023) / 1024)).append("\t").append(data.m_path); + // Round up to the next KiByte: + line.appendInt(int((data.m_sizes + 1023) / 1024)).append("\t").append( + data.m_path); } /** @@ -1345,12 +1334,12 @@ void formatLikeDu(const ReDirStatisticData& data, * @param line OUT: the formatted line, the conclusion of the statistic data */ void formatWithSizeFilesAndDirs(const ReDirStatisticData& data, - ReDirStatistic& parent, ReByteBuffer& line){ + ReDirStatistic& parent, ReByteBuffer& line) { line.setLength(0); - // Round up to the next KiByte: - char buffer[256]; - _snprintf(buffer, sizeof buffer, "%14.6f MB %7d %7d\t", - data.m_sizes / 1E6, data.m_files, data.m_directories); + // Round up to the next KiByte: + char buffer[256]; + _snprintf(buffer, sizeof buffer, "%14.6f MB %7d %7d\t", data.m_sizes / 1E6, + data.m_files, data.m_directories); line.append(buffer, -1).append(data.m_path); } /** @@ -1359,34 +1348,30 @@ void formatWithSizeFilesAndDirs(const ReDirStatisticData& data, * @param logger logger for error handling */ ReDirTouch::ReDirTouch(ReLogger* logger) : - ReTool(s_touchUsage, s_touchExamples, 1, 0, 0, false, logger), - m_buffer() - //m_modified() - //m_accessed() + ReTool(s_touchUsage, s_touchExamples, 1, 0, 0, false, logger), + m_buffer() +//m_modified() +//m_accessed() { setFiletimeUndef(m_modified); setFiletimeUndef(m_accessed); // standard short options: D d O o P p T t v y Z z - m_programArgs.addString("accessed", - i18n("the new access time.\n" - "Formats: absolute, relative to now, relative to the current filetime\n" - "[yyyy.mm.dd/]HH:MM:SS \n" - "now-{s|m|h|d}\n" - "{+|-}{s|m|h|d}"), - 'a', "--accessed", false, NULL); - m_programArgs.addString("modified", - i18n("the new modification time.\n" - "Formats: absolute, relative to now, relative to the current filetime\n" - "[yyyy.mm.dd/]HH:MM:SS\n" - "now-{s|m|h|d}\n" - "{+|-}{s|m|h|d}"), - 'm', "--modified", false, NULL); - addStandardFilterOptions(); + m_programArgs.addString("accessed", i18n("the new access time.\n" + "Formats: absolute, relative to now, relative to the current filetime\n" + "[yyyy.mm.dd/]HH:MM:SS \n" + "now-{s|m|h|d}\n" + "{+|-}{s|m|h|d}"), 'a', "--accessed", false, NULL); + m_programArgs.addString("modified", i18n("the new modification time.\n" + "Formats: absolute, relative to now, relative to the current filetime\n" + "[yyyy.mm.dd/]HH:MM:SS\n" + "now-{s|m|h|d}\n" + "{+|-}{s|m|h|d}"), 'm', "--modified", false, NULL); + addStandardFilterOptions(); } /** * Sets the filetime for the specified files. */ -void ReDirTouch::doIt(){ +void ReDirTouch::doIt() { ReByteBuffer buffer; if (m_programArgs.getString("modified", buffer)[0] != '\0') m_modified = checkDate(buffer.str()); @@ -1403,24 +1388,25 @@ void ReDirTouch::doIt(){ * * @param entry the properties of the directory to process */ -void ReDirTouch::processDir(ReDirStatus_t* entry){ +void ReDirTouch::processDir(ReDirStatus_t* entry) { processFile(entry); } -static bool isAbsoluteTime(ReFileTime_t& time){ +static bool isAbsoluteTime(ReFileTime_t& time) { #if defined __linux__ - static struct tm year1980 = { 0, 0, 0, 1, 1 - 1, 1980-1900 }; + static struct tm year1980 = {0, 0, 0, 1, 1 - 1, 1980-1900}; static time_t time1980 = mktime(&year1980); return time.tv_sec >= time1980; #elif defined __WIN32__ - static ReFileTime_t filetime1980 = { 2148603904, 27846551 }; + static ReFileTime_t filetime1980 = {2148603904, 27846551}; bool rc = time > filetime1980; return rc; #endif } -static void addRelativeTime(ReFileTime_t& absTime, const ReFileTime_t& relTime){ +static void addRelativeTime(ReFileTime_t& absTime, + const ReFileTime_t& relTime) { #if defined __linux__ - if ( (absTime.tv_nsec += relTime.tv_nsec) >= 1000*1000*1000){ + if ( (absTime.tv_nsec += relTime.tv_nsec) >= 1000*1000*1000) { absTime.tv_nsec -= 1000*1000*1000; absTime.tv_sec += 1; } @@ -1429,8 +1415,8 @@ static void addRelativeTime(ReFileTime_t& absTime, const ReFileTime_t& relTime){ uint64_t absValue = ((uint64_t) absTime.dwHighDateTime << 32) | absTime.dwLowDateTime; uint64_t relValue = ((uint64_t) relTime.dwHighDateTime << 32) | relTime.dwLowDateTime; absValue += relValue; - absTime.dwHighDateTime = (uint32_t) (absValue >> 32); - absTime.dwLowDateTime = (uint32_t) absValue; + absTime.dwHighDateTime = (uint32_t) (absValue >> 32); + absTime.dwLowDateTime = (uint32_t) absValue; #endif } /** @@ -1438,10 +1424,10 @@ static void addRelativeTime(ReFileTime_t& absTime, const ReFileTime_t& relTime){ * * @param entry the properties of the file to process */ -void ReDirTouch::processFile(ReDirStatus_t* entry){ +void ReDirTouch::processFile(ReDirStatus_t* entry) { ReFileTime_t modified = *entry->modified(); int countTimes = 0; - if (! filetimeIsUndefined(m_modified)){ + if (!filetimeIsUndefined(m_modified)) { countTimes++; if (isAbsoluteTime(m_modified)) modified = m_modified; @@ -1449,7 +1435,7 @@ void ReDirTouch::processFile(ReDirStatus_t* entry){ addRelativeTime(modified, m_modified); } ReFileTime_t accessed = *entry->accessed(); - if (! filetimeIsUndefined(m_accessed)){ + if (!filetimeIsUndefined(m_accessed)) { countTimes++; if (isAbsoluteTime(m_accessed)) accessed = m_accessed; @@ -1458,19 +1444,19 @@ void ReDirTouch::processFile(ReDirStatus_t* entry){ } const char* name = entry->fullName(); if (touch(name, modified, accessed, ReLogger::globalLogger()) == 0 - && m_verboseLevel >= V_NORMAL){ + && m_verboseLevel >= V_NORMAL) { ReByteBuffer bufferTime; ReByteBuffer bufferTime2; - if (m_verboseLevel == V_NORMAL){ + if (m_verboseLevel == V_NORMAL) { if (countTimes == 2) fprintf(m_output, "%s | %s | %s\n", - ReDirStatus_t::filetimeToString(&modified, bufferTime), - ReDirStatus_t::filetimeToString(&accessed, bufferTime2), - name); + ReDirStatus_t::filetimeToString(&modified, bufferTime), + ReDirStatus_t::filetimeToString(&accessed, bufferTime2), + name); else { ReDirStatus_t::filetimeToString( - filetimeIsUndefined(m_modified) ? &accessed : &modified, - bufferTime); + filetimeIsUndefined(m_modified) ? &accessed : &modified, + bufferTime); fprintf(m_output, "%s %s\n", bufferTime.str(), name); } } else { @@ -1478,15 +1464,17 @@ void ReDirTouch::processFile(ReDirStatus_t* entry){ ReByteBuffer bufferTime4; if (countTimes == 2) fprintf(m_output, "%s -> %s | %s -> %s | %s\n", - ReDirStatus_t::filetimeToString(entry->modified(), bufferTime), - ReDirStatus_t::filetimeToString(&modified, bufferTime2), - ReDirStatus_t::filetimeToString(entry->accessed(), bufferTime3), - ReDirStatus_t::filetimeToString(&accessed, bufferTime4), - name); + ReDirStatus_t::filetimeToString(entry->modified(), + bufferTime), + ReDirStatus_t::filetimeToString(&modified, bufferTime2), + ReDirStatus_t::filetimeToString(entry->accessed(), + bufferTime3), + ReDirStatus_t::filetimeToString(&accessed, bufferTime4), + name); else { ReDirStatus_t::filetimeToString( - filetimeIsUndefined(m_modified) ? &m_accessed : &m_modified, - bufferTime); + filetimeIsUndefined(m_modified) ? &m_accessed : &m_modified, + bufferTime); fprintf(m_output, "%s -> %s %s\n", bufferTime.str(), name); } } @@ -1501,7 +1489,7 @@ void ReDirTouch::processFile(ReDirStatus_t* entry){ * @param logger NULL or the logger */ ReErrNo_t ReDirTouch::touch(const char* filename, const ReFileTime_t& modified, - const ReFileTime_t& accessed, ReLogger* logger){ + const ReFileTime_t& accessed, ReLogger* logger) { #if defined __linux__ timeval times[2]; times[0].tv_sec = accessed.tv_sec; @@ -1516,38 +1504,36 @@ ReErrNo_t ReDirTouch::touch(const char* filename, const ReFileTime_t& modified, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) - rc = GetLastError(); + rc = GetLastError(); else { if (! SetFileTime(handle, (LPFILETIME) NULL, &accessed, &modified)) - rc = GetLastError(); + rc = GetLastError(); CloseHandle(handle); } #endif if (rc != 0 && logger != NULL) logger->sayF(LOG_ERROR | CAT_FILE, LC_TOUCH_1, - i18n("cannot change filetime: $1 (errno: $2)")).arg(filename) - .arg(errno).end(); + i18n("cannot change filetime: $1 (errno: $2)")).arg(filename).arg( + errno).end(); return rc; } - - /** * Prints a vector of lines. * * @param lines a vector of lines without newline ('\n') */ -static void printField(const char** lines){ - for (int ix = 0; lines[ix] != NULL; ix++){ - printf("%s\n", lines[ix]); - } +static void printField(const char** lines) { + for (int ix = 0; lines[ix] != NULL; ix++) { + printf("%s\n", lines[ix]); + } } /** * Prints a message how to use the module and exits. */ -void ReDirTools::usage(ReTool& tool){ - tool.programArgs().help(NULL, false, stdout); +void ReDirTools::usage(ReTool& tool) { + tool.programArgs().help(NULL, false, stdout); } /** @@ -1556,13 +1542,13 @@ void ReDirTools::usage(ReTool& tool){ * @param msg an error message * @param msg2 an addition to the error message or NULL */ -void ReDirTools::usage(const char* msg, const char* msg2){ - printf ("Version: %s\n", m_version); - printf ("usage: dirtool \n" +void ReDirTools::usage(const char* msg, const char* msg2) { + printf("Version: %s\n", m_version); + printf("usage: dirtool \n" "call 'dirtool help' for more info\n"); - if (msg != NULL) - printf ("+++ %s%s\n", msg, msg2 == NULL ? "" : msg2); - exit(1); + if (msg != NULL) + printf("+++ %s%s\n", msg, msg2 == NULL ? "" : msg2); + exit(1); } /** @@ -1571,8 +1557,8 @@ void ReDirTools::usage(const char* msg, const char* msg2){ * @param path the name of the subdir to create */ void ReDirSync::makeDirWithParents(ReByteBuffer& path, int minWidth, - ReTraverser& traverser){ - if (! exists(path)){ + ReTraverser& traverser) { + if (!exists(path)) { ReFileProperties_t* props = NULL; #if defined __linux__ ReDirStatus_t* entry = traverser.topOfStack(); @@ -1587,28 +1573,27 @@ void ReDirSync::makeDirWithParents(ReByteBuffer& path, int minWidth, * @param logger logger for error handling */ ReDirSync::ReDirSync(ReLogger* logger) : - ReTool(s_syncUsage, s_syncExamples, 2, 0, 1, false, logger), - m_buffer() -{ + ReTool(s_syncUsage, s_syncExamples, 2, 0, 1, false, logger), + m_buffer() { // standard short options: D d O o P p T t v y Z z - m_buffer.ensureSize(4u*1024u*1024u); - m_programArgs.addBool("add", - i18n("copies only files which does not exist on the target"), - 'a', "add", false); - m_programArgs.addBool("dry", - i18n("does nothing, but says what should be done"), - 'Y', "dry", false); - m_programArgs.addInt("timediff", - i18n("filetime difference is considered to be equal\n" - "if the difference is less than this value (in seconds)"), - 'I', "time-delta", 2); - m_programArgs.addBool("ignoredate", - i18n("the modification is recognized only by the different size (not time)"), - 'i', "ignore-time", false); - m_programArgs.addBool("mustexist", - i18n("files which don't exist on the target will not be copied"), - 'm', "must-exist", false); - addStandardFilterOptions(); + m_buffer.ensureSize(4u * 1024u * 1024u); + m_programArgs.addBool("add", + i18n("copies only files which does not exist on the target"), 'a', + "add", false); + m_programArgs.addBool("dry", + i18n("does nothing, but says what should be done"), 'Y', "dry", false); + m_programArgs.addInt("timediff", + i18n("filetime difference is considered to be equal\n" + "if the difference is less than this value (in seconds)"), 'I', + "time-delta", 2); + m_programArgs.addBool("ignoredate", + i18n( + "the modification is recognized only by the different size (not time)"), + 'i', "ignore-time", false); + m_programArgs.addBool("mustexist", + i18n("files which don't exist on the target will not be copied"), 'm', + "must-exist", false); + addStandardFilterOptions(); } /** @@ -1617,7 +1602,7 @@ ReDirSync::ReDirSync(ReLogger* logger) : * @param entry the source file info * @param target the name of the target file */ -void ReDirSync::copyFile(ReDirStatus_t* entry, const char* target){ +void ReDirSync::copyFile(ReDirStatus_t* entry, const char* target) { ReFileProperties_t* props; #ifdef __linux__ props = &entry->m_status; @@ -1629,7 +1614,7 @@ void ReDirSync::copyFile(ReDirStatus_t* entry, const char* target){ props = &properties; #endif copyFile(entry->fullName(), props, target, m_buffer, - ReLogger::globalLogger()); + ReLogger::globalLogger()); } /** @@ -1645,53 +1630,53 @@ void ReDirSync::copyFile(ReDirStatus_t* entry, const char* target){ * falseerror occurred */ bool ReDirSync::copyFile(const char* source, ReFileProperties_t* properties, - const char* target, ReByteBuffer& buffer, ReLogger* logger){ + const char* target, ReByteBuffer& buffer, ReLogger* logger) { bool rc = false; #ifdef __linux__ struct stat info; - if (properties == NULL){ + if (properties == NULL) { if (stat(source, &info) == 0) - properties = &info; + properties = &info; else { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_1, - i18n("could not find: $1 (errno: $2)")).arg(source) - .arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_1, + i18n("could not find: $1 (errno: $2)")).arg(source) + .arg(errno).end(); } } FILE* fpSource = fopen(source, "rb"); - if (fpSource == NULL){ + if (fpSource == NULL) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_2, - i18n("cannot open $1 (errno: $2)")) - .arg(source).arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_2, + i18n("cannot open $1 (errno: $2)")) + .arg(source).arg(errno).end(); } else { ReFileSize_t size = properties == NULL ? 0x7fffffff : properties->st_size; FILE* fpTarget = fopen(target, "w"); - if (fpTarget == NULL){ + if (fpTarget == NULL) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_3, - i18n("cannot open $1 (errno: $2)")) - .arg(target).arg(errno).end(); - } else{ - while(size > 0){ + logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_3, + i18n("cannot open $1 (errno: $2)")) + .arg(target).arg(errno).end(); + } else { + while(size > 0) { size_t blockSize = buffer.capacity(); if ((int) blockSize > size) - blockSize = size; - if (fread(buffer.buffer(), blockSize, 1, fpSource) != 1){ + blockSize = size; + if (fread(buffer.buffer(), blockSize, 1, fpSource) != 1) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_5, - i18n("cannot read $1 (errno: $2)")) - .arg(source).arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_5, + i18n("cannot read $1 (errno: $2)")) + .arg(source).arg(errno).end(); break; } size_t written; if ((written = fwrite(buffer.buffer(), 1, blockSize, - fpTarget)) != blockSize){ + fpTarget)) != blockSize) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_6, - i18n("cannot write $1 [$2] (errno: $3)")) - .arg(target).arg(written).arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_6, + i18n("cannot write $1 [$2] (errno: $3)")) + .arg(target).arg(written).arg(errno).end(); break; } size -= blockSize; @@ -1699,16 +1684,16 @@ bool ReDirSync::copyFile(const char* source, ReFileProperties_t* properties, rc = size == 0ll; fclose(fpTarget); if (properties != NULL) - setProperties(target, properties, logger); + setProperties(target, properties, logger); } fclose(fpSource); } #elif defined __WIN32__ - BOOL cancel = false; - rc = CopyFileExA(source, target, NULL, NULL, &cancel, COPY_FILE_NO_BUFFERING) != 0; - int errNo = 0; - if (! rc) - errNo = GetLastError(); + BOOL cancel = false; + rc = CopyFileExA(source, target, NULL, NULL, &cancel, COPY_FILE_NO_BUFFERING) != 0; + int errNo = 0; + if (! rc) + errNo = GetLastError(); #endif return rc; } @@ -1722,7 +1707,7 @@ bool ReDirSync::copyFile(const char* source, ReFileProperties_t* properties, * false: error occurred */ bool ReDirSync::setProperties(const char* fullName, - ReFileProperties_t* properties, ReLogger* logger){ + ReFileProperties_t* properties, ReLogger* logger) { bool rc = true; #if defined __linux__ timeval times[2]; @@ -1730,26 +1715,26 @@ bool ReDirSync::setProperties(const char* fullName, times[0].tv_usec = properties->st_atim.tv_nsec / 1000; times[1].tv_sec = properties->st_mtim.tv_sec; times[1].tv_usec = properties->st_mtim.tv_nsec / 1000; - if (utimes(fullName, times) != 0){ + if (utimes(fullName, times) != 0) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_1, - i18n("cannot change file times: $1 (errno: $2)")) - .arg(fullName).arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_1, + i18n("cannot change file times: $1 (errno: $2)")) + .arg(fullName).arg(errno).end(); rc = false; } int rights = properties->st_mode & (S_IRWXO | S_IRWXG | S_IRWXU); if (chmod(fullName, rights) != 0) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_2, - i18n("cannot change file modes: $1 (errno: $2)")) - .arg(fullName).arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_2, + i18n("cannot change file modes: $1 (errno: $2)")) + .arg(fullName).arg(errno).end(); rc = false; } - if (chown(fullName, properties->st_uid, properties->st_gid) != 0){ + if (chown(fullName, properties->st_uid, properties->st_gid) != 0) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_3, - i18n("cannot change file owner: $1 (errno: $2)")) - .arg(fullName).arg(errno).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_3, + i18n("cannot change file owner: $1 (errno: $2)")) + .arg(fullName).arg(errno).end(); rc = false; } #endif @@ -1766,7 +1751,7 @@ bool ReDirSync::setProperties(const char* fullName, * falseerror occurred */ bool ReDirSync::makeDirectory(const char* directory, int minLength, - ReFileProperties_t* properties, ReLogger* logger){ + ReFileProperties_t* properties, ReLogger* logger) { bool rc = true; ReByteBuffer path(directory); int start = 0; @@ -1777,24 +1762,24 @@ bool ReDirSync::makeDirectory(const char* directory, int minLength, int ixSlash = start < 0 ? 0 : start; struct stat info; // for all parents and the full path itself: - while(ixSlash >= 0){ + while (ixSlash >= 0) { ixSlash = path.indexOf(OS_SEPARATOR_CHAR, ixSlash + 1); // is the slash in front of the first node, e.g. 'e:\'? if (ixSlash == start + 1) // not a real node: take the next node ixSlash = path.indexOf(OS_SEPARATOR_CHAR, ixSlash + 1); - if (ixSlash >= 0){ + if (ixSlash >= 0) { // we handle only the next node: path.buffer()[ixSlash] = '\0'; } // does the node exist? - if (lstat(path.str(), &info) != 0){ + if (lstat(path.str(), &info) != 0) { // no, then we make it: - if (_mkdir(path.str(), ALLPERMS) != 0){ + if (_mkdir(path.str(), ALLPERMS) != 0) { if (logger != NULL) logger->sayF(LOG_ERROR | CAT_FILE, LC_MAKE_DIR_1, - i18n("could not make directory $1 (errno: $2)")) - .arg(path.str()).arg(errno).end(); + i18n("could not make directory $1 (errno: $2)")).arg( + path.str()).arg(errno).end(); rc = false; break; } else { @@ -1803,7 +1788,7 @@ bool ReDirSync::makeDirectory(const char* directory, int minLength, #endif } } - if (ixSlash >= 0){ + if (ixSlash >= 0) { // restore the full path: path.buffer()[ixSlash] = OS_SEPARATOR_CHAR; } @@ -1814,15 +1799,15 @@ bool ReDirSync::makeDirectory(const char* directory, int minLength, /** * Synchronizes two directory trees. */ -void ReDirSync::doIt(){ - ReDirEntryFilter_t filter; - const char* sep = OS_SEPARATOR; +void ReDirSync::doIt() { + ReDirEntryFilter_t filter; + const char* sep = OS_SEPARATOR; ReByteBuffer buffer; ReByteBuffer target(m_programArgs.getArg(m_programArgs.getArgCount() - 1)); target.removeLastChar(OS_SEPARATOR_CHAR); - if (! exists(target)) + if (!exists(target)) help(i18n("target does not exist: $1"), target.str()); - else if (! S_ISDIR(m_statInfo.st_mode)) + else if (!S_ISDIR(m_statInfo.st_mode)) help(i18n("target is not a directory: $1"), target.str()); size_t lengthTargetBase = target.length(); bool addOnly = m_programArgs.getBool("add"); @@ -1837,17 +1822,17 @@ void ReDirSync::doIt(){ int treeDirs = 0; int64_t treeSumSizes = 0ll; ReByteBuffer source, targetFile; - for (int ix = 0; ix < m_programArgs.getArgCount() - 1; ix++){ + for (int ix = 0; ix < m_programArgs.getArgCount() - 1; ix++) { source.set(m_programArgs.getArg(ix), -1); target.setLength(lengthTargetBase); bool endsWithSlash = source.endsWith(sep, 1); if (endsWithSlash) source.reduceLength(); - if (! exists(source)) + if (!exists(source)) help(i18n("source does not exist: $1"), source.str()); - else if (! S_ISDIR(m_statInfo.st_mode)) + else if (!S_ISDIR(m_statInfo.st_mode)) help(i18n("source is not a directory: $1"), source.str()); - if (! endsWithSlash){ + if (!endsWithSlash) { // the basename of the source will be appended to the target: int startNode = source.rindexOf(sep, 1, 0, source.length() - 1); target.appendChar(OS_SEPARATOR_CHAR); @@ -1861,62 +1846,72 @@ void ReDirSync::doIt(){ int level; ReDirStatus_t* entry; ReByteBuffer line; - while( (entry = m_traverser.nextFile(level, &filter)) != NULL){ + while ((entry = m_traverser.nextFile(level, &filter)) != NULL) { if (entry->isDirectory()) continue; // append the new relative path from source to target: target.setLength(ixTargetRelative); target.append(entry->m_path.str() + ixSourceRelative, -1); - if (! exists(target)) + if (!exists(target)) makeDirWithParents(target, ixTargetRelative, m_traverser); targetFile.set(target).append(entry->node(), -1); - const char* targetRelativePath = targetFile.str() + ixTargetRelative + 1; + const char* targetRelativePath = targetFile.str() + ixTargetRelative + + 1; bool targetExists = exists(targetFile); - if (! targetExists && mustExist){ + if (!targetExists && mustExist) { if (m_verboseLevel == V_CHATTER) - fprintf(m_output, "-ignored: %s does not exist\n", targetRelativePath); + fprintf(m_output, "-ignored: %s does not exist\n", + targetRelativePath); continue; } - if (targetExists){ - if (addOnly){ + if (targetExists) { + if (addOnly) { if (m_verboseLevel >= V_CHATTER) - fprintf(m_output, "~ignored: %s exists\n", targetRelativePath); + fprintf(m_output, "~ignored: %s exists\n", + targetRelativePath); continue; } - if (ignoreDate && entry->fileSize() == m_statInfo.st_size){ + if (ignoreDate && entry->fileSize() == m_statInfo.st_size) { if (m_verboseLevel >= V_CHATTER) - fprintf(m_output, "_ignored: %s same size\n", targetRelativePath); + fprintf(m_output, "_ignored: %s same size\n", + targetRelativePath); continue; } // target younger than source? - int diff = int(m_statInfo.st_mtime - entry->filetimeToTime(entry->modified())); - if (! ignoreDate && m_statInfo.st_mtime - entry->filetimeToTime(entry->modified()) - <= maxFileTimeDiff) { + int diff = int( + m_statInfo.st_mtime + - entry->filetimeToTime(entry->modified())); + if (!ignoreDate + && m_statInfo.st_mtime + - entry->filetimeToTime(entry->modified()) + <= maxFileTimeDiff) { if (m_verboseLevel >= V_CHATTER) - fprintf(m_output, "=ignored: %s same time\n", targetRelativePath); + fprintf(m_output, "=ignored: %s same time\n", + targetRelativePath); continue; } } files++; sumSizes += entry->fileSize(); if (m_verboseLevel >= V_NORMAL) - fprintf(m_output, "%c%s%s\n", targetExists ? '!' : '+', targetRelativePath, - dry ? " would be copied" : ""); - if (! dry) + fprintf(m_output, "%c%s%s\n", targetExists ? '!' : '+', + targetRelativePath, dry ? " would be copied" : ""); + if (!dry) copyFile(entry, targetFile.str()); } treeFiles += m_traverser.files(); treeDirs += m_traverser.directories(); - treeSumSizes+= m_traverser.sizes(); + treeSumSizes += m_traverser.sizes(); } - if (m_verboseLevel >= V_SUMMARY){ + if (m_verboseLevel >= V_SUMMARY) { int duration = int(time(NULL) - m_start); - fprintf(m_output, i18n( - "=== copied: %02d:%02d sec %7d file(s) %12.6f MByte (%.3f MB/sec).\n" - "=== tree: %5d dir(s) %7d file(s) %12.6f MByte\n"), - duration / 60, duration % 60, files, sumSizes / 1E6, - sumSizes / 1E6 / (duration == 0 ? 1 : duration), - treeDirs, treeFiles, treeSumSizes / 1E6); + fprintf(m_output, + i18n( + "=== copied: %02d:%02d sec %7d file(s) %12.6f MByte (%.3f MB/sec).\n" + "=== tree: %5d dir(s) %7d file(s) %12.6f MByte\n"), + duration / 60, duration % 60, files, sumSizes / 1E6, + sumSizes / 1E6 / (duration == 0 ? 1 : duration), treeDirs, + treeFiles, treeSumSizes / 1E6); } } @@ -1926,15 +1921,13 @@ void ReDirSync::doIt(){ * @param logger logger for error handling */ ReDirWhich::ReDirWhich(ReLogger* logger) : - ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger) -{ + ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger) { // no standard options: - m_programArgs.addBool("all", - i18n("all files will be found, not only the first"), - 'a', "all", false); - m_programArgs.addString("list", - i18n("a path list (separator see option 'separator'"), - 'l', "list", false, NULL); + m_programArgs.addBool("all", + i18n("all files will be found, not only the first"), 'a', "all", false); + m_programArgs.addString("list", + i18n("a path list (separator see option 'separator'"), 'l', "list", + false, NULL); m_programArgs.addString("separator", i18n("separator between the path elements"), 's', "separator", false, @@ -1943,23 +1936,22 @@ ReDirWhich::ReDirWhich(ReLogger* logger) : #elif defined __WIN32__ ";" #endif - ); - m_programArgs.addString("variable", - i18n("variable with the path list"), - 'v', "variable", false, "PATH"); + ); + m_programArgs.addString("variable", i18n("variable with the path list"), + 'v', "variable", false, "PATH"); m_hasStandardArgs = false; } /** * Creates the batch file. */ -void ReDirWhich::doIt(){ +void ReDirWhich::doIt() { ReByteBuffer value, path; bool all = false; ReStringList items; char sep = 0; m_programArgs.getString("list", path); - if (path.length() == 0){ + if (path.length() == 0) { m_programArgs.getString("variable", value); if (getenv(value.str()) == NULL) help("Umgebungsvariable nicht definiert: ", value.str()); @@ -1971,13 +1963,13 @@ void ReDirWhich::doIt(){ items.split(path.str(), sep); struct stat info; ReByteBuffer full; - for (int ix = 0; ix < m_programArgs.getArgCount(); ix++){ + for (int ix = 0; ix < m_programArgs.getArgCount(); ix++) { bool found = false; ReByteBuffer arg(m_programArgs.getArg(ix)); - for (size_t ixItem = 0; ixItem < items.count(); ixItem++){ + for (size_t ixItem = 0; ixItem < items.count(); ixItem++) { full.set(items.strOf(ixItem)); - if (arg.indexOf('*') < 0){ + if (arg.indexOf('*') < 0) { full.ensureLastChar(OS_SEPARATOR_CHAR); full.append(arg); found = stat(full.str(), &info) == 0; @@ -1985,13 +1977,14 @@ void ReDirWhich::doIt(){ printf("%s\n", full.str()); } else { ReDirectory dir(full.str()); - if (dir.findFirst(arg.str(), false)){ + if (dir.findFirst(arg.str(), false)) { do { - printf("%s%c%s\n", full.str(), OS_SEPARATOR_CHAR, dir.currentFile()); - } while(dir.findNext()); + printf("%s%c%s\n", full.str(), OS_SEPARATOR_CHAR, + dir.currentFile()); + } while (dir.findNext()); } } - if (found && ! all) + if (found && !all) break; } } @@ -2003,10 +1996,10 @@ void ReDirWhich::doIt(){ * @param part the part to test * @return true: part is a prefix of full */ -static bool isArg(const char* full, const char* part){ - ReByteBuffer fullArg(full); - bool rc = fullArg.startsWith(part, -1); - return rc; +static bool isArg(const char* full, const char* part) { + ReByteBuffer fullArg(full); + bool rc = fullArg.startsWith(part, -1); + return rc; } /** @@ -2015,39 +2008,39 @@ static bool isArg(const char* full, const char* part){ * @param argc the number of arguments * @param argav the argument vector */ -void ReDirTools::help(int argc, const char* argv[]){ - if (argc <= 1) - printField(s_helpSummary); - else { - argc--; - argv++; - const char* arg0 = argv[0]; - if (isArg("batch", arg0)){ - ReDirBatch batch(m_logger); - batch.help(NULL); - } else if (isArg("list", arg0)){ - ReDirList list(m_logger); - list.help(NULL); - } else if (isArg("help", arg0)){ - printField(s_helpSummary); - } else if (isArg("md5", arg0)){ - ReDirMD5 md5(m_logger); - md5.help(NULL); - } else if (isArg("statistic", arg0)){ - ReDirStatistic stat(m_logger); - stat.help(NULL); - } else if (isArg("test", arg0)){ - void testAll(); - testAll(); - } else if (isArg("touch", arg0)){ - ReDirTouch touch(m_logger); - touch.help(NULL); - } else if (isArg("which", arg0)){ - ReDirWhich which(m_logger); - which.help(NULL); - } else - printf("+++ unknown sub command: %s\n", arg0); - } +void ReDirTools::help(int argc, const char* argv[]) { + if (argc <= 1) + printField(s_helpSummary); + else { + argc--; + argv++; + const char* arg0 = argv[0]; + if (isArg("batch", arg0)) { + ReDirBatch batch(m_logger); + batch.help(NULL); + } else if (isArg("list", arg0)) { + ReDirList list(m_logger); + list.help(NULL); + } else if (isArg("help", arg0)) { + printField(s_helpSummary); + } else if (isArg("md5", arg0)) { + ReDirMD5 md5(m_logger); + md5.help(NULL); + } else if (isArg("statistic", arg0)) { + ReDirStatistic stat(m_logger); + stat.help(NULL); + } else if (isArg("test", arg0)) { + void testAll(); + testAll(); + } else if (isArg("touch", arg0)) { + ReDirTouch touch(m_logger); + touch.help(NULL); + } else if (isArg("which", arg0)) { + ReDirWhich which(m_logger); + which.help(NULL); + } else + printf("+++ unknown sub command: %s\n", arg0); + } } /** @@ -2057,7 +2050,7 @@ void ReDirTools::help(int argc, const char* argv[]){ * @param argv the argument vector * @param tool the tool which realizes the command */ -void ReDirTools::run(int argc, const char* argv[], ReTool& tool){ +void ReDirTools::run(int argc, const char* argv[], ReTool& tool) { tool.run(argc, argv); } /** @@ -2066,38 +2059,38 @@ void ReDirTools::run(int argc, const char* argv[], ReTool& tool){ * @param argc the number of arguments * @param orgArgv the argument vector */ -int ReDirTools::main(int argc, char* orgArgv[]){ - ReDirTools tools; - const char** argv = (const char**) orgArgv; - if (argc < 2){ - tools.help(0, argv); - exit(1); - } - argc--; - argv++; +int ReDirTools::main(int argc, char* orgArgv[]) { + ReDirTools tools; + const char** argv = (const char**) orgArgv; + if (argc < 2) { + tools.help(0, argv); + exit(1); + } + argc--; + argv++; m_logger = ReLogger::globalLogger(); - const char* arg0 = argv[0]; - if (isArg("batch", arg0)) - ReDirBatch(m_logger).run(argc, argv); - else if (isArg("help", arg0)) - tools.help(argc, argv); - else if (isArg("list", arg0)) - ReDirList(m_logger).run(argc, argv); - else if (isArg("md5", arg0)) - ReDirMD5(m_logger).run(argc, argv); - else if (isArg("statistic", arg0)) - ReDirStatistic(m_logger).run(argc, argv); - else if (isArg("synchronize", arg0)) - ReDirSync(m_logger).run(argc, argv); - else if (isArg("touch", arg0)) - ReDirTouch(m_logger).run(argc, argv); - else if (isArg("which", arg0)) - ReDirWhich(m_logger).run(argc, argv); - else if (isArg("test", arg0)){ - void testAll(); - testAll(); - }else - tools.usage("unknown command: ", argv[1]); - return 0; + const char* arg0 = argv[0]; + if (isArg("batch", arg0)) + ReDirBatch(m_logger).run(argc, argv); + else if (isArg("help", arg0)) + tools.help(argc, argv); + else if (isArg("list", arg0)) + ReDirList(m_logger).run(argc, argv); + else if (isArg("md5", arg0)) + ReDirMD5(m_logger).run(argc, argv); + else if (isArg("statistic", arg0)) + ReDirStatistic(m_logger).run(argc, argv); + else if (isArg("synchronize", arg0)) + ReDirSync(m_logger).run(argc, argv); + else if (isArg("touch", arg0)) + ReDirTouch(m_logger).run(argc, argv); + else if (isArg("which", arg0)) + ReDirWhich(m_logger).run(argc, argv); + else if (isArg("test", arg0)) { + void testAll(); + testAll(); + } else + tools.usage("unknown command: ", argv[1]); + return 0; } diff --git a/os/ReDirTools.hpp b/os/ReDirTools.hpp index 0f1a5d8..9e7cfe8 100644 --- a/os/ReDirTools.hpp +++ b/os/ReDirTools.hpp @@ -10,7 +10,7 @@ #ifndef OS_DIRTOOLS_HPP_ #define OS_DIRTOOLS_HPP_ -class ReDirOptions : public ReTraceUnit{ +class ReDirOptions: public ReTraceUnit { public: enum VerboseLevel { V_UNDEF, @@ -21,43 +21,46 @@ public: V_DEBUG }; public: - ReDirOptions(const char* usage[], const char* example[]); - ~ReDirOptions(); + ReDirOptions(const char* usage[], const char* example[]); + ~ReDirOptions(); public: - void addCompoundUsage(const char** usage); - void addStandardFilterOptions(); - ReFileTime_t checkDate(const char* value); - const char* checkPatternList(const char* value); - int64_t checkSize(const char* value); - void checkStandardFilterOptions(); - ReDirStatus_t::Type_t checkType(const char* value); + void addCompoundUsage(const char** usage); + void addStandardFilterOptions(); + ReFileTime_t checkDate(const char* value); + const char* checkPatternList(const char* value); + int64_t checkSize(const char* value); + void checkStandardFilterOptions(); + ReDirStatus_t::Type_t checkType(const char* value); void close(); /** Returns the compound usage message. * @return the compound usage message */ - const char** compoundUsage() const - { return m_compoundUsage; } - void initCompoundUsage(size_t size); - void help(const char* errorMessage, const char* message2 = NULL) const; + const char** compoundUsage() const { + return m_compoundUsage; + } + void initCompoundUsage(size_t size); + void help(const char* errorMessage, const char* message2 = NULL) const; /** Returns the program arguments. * @return the program arguments */ - const ReProgramArgs& programArgs() const - { return m_programArgs; } + const ReProgramArgs& programArgs() const { + return m_programArgs; + } /** Returns the program arguments. * @return the program arguments */ - ReProgramArgs& programArgsChangeable() - { return m_programArgs; } - void setFilterFromProgramArgs(ReDirEntryFilter_t& filter); + ReProgramArgs& programArgsChangeable() { + return m_programArgs; + } + void setFilterFromProgramArgs(ReDirEntryFilter_t& filter); protected: - void optimizePathPattern(ReByteBuffer& buffer); + void optimizePathPattern(ReByteBuffer& buffer); protected: - ReProgramArgs m_programArgs; - RePatternList m_nodePatterns; - RePatternList m_pathPatterns; - const char** m_compoundUsage; - int m_countCompoundUsage; + ReProgramArgs m_programArgs; + RePatternList m_nodePatterns; + RePatternList m_pathPatterns; + const char** m_compoundUsage; + int m_countCompoundUsage; FILE* m_output; VerboseLevel m_verboseLevel; }; @@ -75,11 +78,11 @@ typedef struct { /** * Base class of directory tools. */ -class ReTool : public ReDirOptions, public ReDirTreeStatistic { +class ReTool: public ReDirOptions, public ReDirTreeStatistic { public: - ReTool(const char* usage[], const char* example[], - int minArguments, int reservedFirst, int reservedLast, - bool addCurrentDirIfNoArguments, ReLogger* logger); + ReTool(const char* usage[], const char* example[], int minArguments, + int reservedFirst, int reservedLast, bool addCurrentDirIfNoArguments, + ReLogger* logger); virtual ~ReTool(); public: virtual bool trace(const char* currentFile); @@ -99,19 +102,19 @@ protected: @param name can be changed and recovered! @return true: a file with the given name exists */ - inline bool exists(ReByteBuffer& name){ + inline bool exists(ReByteBuffer& name) { #if defined __linux__ // linux ignores a trailing slash: return stat(name.str(), &m_statInfo) == 0; #elif defined __WIN32__ int ix = name.length() - 1; if (ix >= 0 && name.str()[ix] != OS_SEPARATOR_CHAR) - ix = -1; + ix = -1; else - name.setLength(ix); + name.setLength(ix); bool rc = stat(name.str(), &m_statInfo) == 0; if (ix >= 0) - name.appendChar(OS_SEPARATOR_CHAR); + name.appendChar(OS_SEPARATOR_CHAR); return rc; #endif } @@ -129,25 +132,25 @@ protected: }; -class ReDirBatch : public ReTool { +class ReDirBatch: public ReTool { public: - ReDirBatch(ReLogger* logger); + ReDirBatch(ReLogger* logger); protected: virtual void doIt(); virtual void processDir(ReDirStatus_t* entry); virtual void processFile(ReDirStatus_t* entry); protected: ReByteBuffer m_arguments; - ReByteBuffer m_script; + ReByteBuffer m_script; bool m_isExe; }; /** * List file attributes of files. */ -class ReDirList : public ReTool { +class ReDirList: public ReTool { public: - ReDirList(ReLogger* logger); + ReDirList(ReLogger* logger); protected: virtual void doIt(); virtual void processDir(ReDirStatus_t* entry); @@ -163,9 +166,9 @@ protected: /** * Calculates the MD5 checksum of files. */ -class ReDirMD5 : public ReTool { +class ReDirMD5: public ReTool { public: - ReDirMD5(ReLogger* logger); + ReDirMD5(ReLogger* logger); protected: virtual void doIt(); virtual void processDir(ReDirStatus_t* entry); @@ -177,26 +180,26 @@ protected: /** * Sychronizes two directory trees. */ -class ReDirSync : public ReTool { +class ReDirSync: public ReTool { public: - ReDirSync(ReLogger* logger); + ReDirSync(ReLogger* logger); protected: virtual void doIt(); void copyFile(ReDirStatus_t* entry, const char* target); void makeDirWithParents(ReByteBuffer& path, int minWidth, - ReTraverser& traverser); + ReTraverser& traverser); public: static bool copyFile(const char* source, ReFileProperties_t* properties, - const char* target, ReByteBuffer& buffer, ReLogger* logger = NULL); + const char* target, ReByteBuffer& buffer, ReLogger* logger = NULL); static bool makeDirectory(const char* directory, int minLength, - ReFileProperties_t* properties, ReLogger* logger = NULL); + ReFileProperties_t* properties, ReLogger* logger = NULL); static bool setProperties(const char* fullName, - ReFileProperties_t* properties, ReLogger* logger = NULL); + ReFileProperties_t* properties, ReLogger* logger = NULL); protected: ReByteBuffer m_buffer; }; -class ReDirStatisticData : public ReDirTreeStatistic { +class ReDirStatisticData: public ReDirTreeStatistic { public: ReDirStatisticData(); ReDirStatisticData(const ReDirStatisticData& source); @@ -210,41 +213,42 @@ public: class ReDirStatistic; extern void formatLikeDu(const ReDirStatisticData& data, ReDirStatistic& parent, - ReByteBuffer& line); + ReByteBuffer& line); extern void formatWithSizeFilesAndDirs(const ReDirStatisticData& data, - ReDirStatistic& parent, ReByteBuffer& line); + ReDirStatistic& parent, ReByteBuffer& line); /** * Calculates a statistic of a directory tree. */ -class ReDirStatistic : public ReTool { +class ReDirStatistic: public ReTool { public: - ReDirStatistic(ReLogger* logger, int deltaList = 512, int deltaBuffer = 0x10000); + ReDirStatistic(ReLogger* logger, int deltaList = 512, int deltaBuffer = + 0x10000); ~ReDirStatistic(); public: const ReStringList& calculate(const char* base, int depth, - void (*format)(const ReDirStatisticData& data, ReDirStatistic& parent, - ReByteBuffer& line) = formatLikeDu); - void doIt(); + void (*format)(const ReDirStatisticData& data, ReDirStatistic& parent, + ReByteBuffer& line) = formatLikeDu); + void doIt(); private: ReStringList m_list; - int m_traceInterval; - time_t m_lastTrace; + int m_traceInterval; + time_t m_lastTrace; }; /** * Changes the filetime of files. */ -class ReDirTouch : public ReTool { +class ReDirTouch: public ReTool { public: - ReDirTouch(ReLogger* logger); + ReDirTouch(ReLogger* logger); protected: virtual void doIt(); virtual void processDir(ReDirStatus_t* entry); virtual void processFile(ReDirStatus_t* entry); public: static ReErrNo_t touch(const char* filename, const ReFileTime_t& modified, - const ReFileTime_t& accessed, ReLogger* logger = NULL); + const ReFileTime_t& accessed, ReLogger* logger = NULL); protected: ReByteBuffer m_buffer; ReFileTime_t m_modified; @@ -254,9 +258,9 @@ protected: /** * Find files in a list (like PATH). */ -class ReDirWhich : public ReTool { +class ReDirWhich: public ReTool { public: - ReDirWhich(ReLogger* logger); + ReDirWhich(ReLogger* logger); protected: virtual void doIt(); }; @@ -264,15 +268,15 @@ protected: class ReDirTools { public: - virtual void usage(const char* msg, const char* msg2 = NULL); - void help(int argc, const char* argv[]); + virtual void usage(const char* msg, const char* msg2 = NULL); + void help(int argc, const char* argv[]); public: - static int main(int argc, char* argv[]); + static int main(int argc, char* argv[]); protected: void run(int argc, const char* argv[], ReTool& tool); void usage(ReTool& tool); public: - static const char* m_version; + static const char* m_version; static ReLogger* m_logger; }; #endif /* OS_DIRTOOLS_HPP_ */ diff --git a/os/ReTraverser.cpp b/os/ReTraverser.cpp index be3bf87..344da80 100644 --- a/os/ReTraverser.cpp +++ b/os/ReTraverser.cpp @@ -16,7 +16,7 @@ #endif enum RELOC_TRAVERSER { - LC_RIGHTS_AS_STRING_1 = LC_TRAVERSER + 1, // 50401 + LC_RIGHTS_AS_STRING_1 = LC_TRAVERSER + 1, // 50401 LC_RIGHTS_AS_STRING_2, // 50402 LC_RIGHTS_AS_STRING_3, // 50403 LC_GET_PRIVILEGE_1, // 50404 @@ -28,20 +28,20 @@ enum RELOC_TRAVERSER { /** * Constructor. -*/ + */ ReDirStatus_t::ReDirStatus_t(ReLogger* logger) : - m_path(), - m_fullName(), - m_passNo(0), - m_logger(logger), +m_path(), +m_fullName(), +m_passNo(0), +m_logger(logger), #ifdef __linux__ - m_handle(NULL), - m_data(NULL) - //m_status; +m_handle(NULL), +m_data(NULL) +//m_status; #elif defined WIN32 - m_handle(INVALID_HANDLE_VALUE), - //m_data; - m_getPrivilege(true) +m_handle(INVALID_HANDLE_VALUE), +//m_data; +m_getPrivilege(true) #endif { #ifdef __linux__ @@ -58,9 +58,9 @@ ReDirStatus_t::ReDirStatus_t(ReLogger* logger) : */ const ReFileTime_t* ReDirStatus_t::accessed() { #ifdef __linux__ - return &(getStatus()->st_atim); + return &(getStatus()->st_atim); #elif defined __WIN32__ - return &m_data.ftLastAccessTime; + return &m_data.ftLastAccessTime; #endif } @@ -71,9 +71,9 @@ const ReFileTime_t* ReDirStatus_t::accessed() { */ ReFileSize_t ReDirStatus_t::fileSize() { #ifdef __linux__ - return getStatus()->st_size; + return getStatus()->st_size; #elif defined __WIN32__ - return ((int64_t) m_data.nFileSizeHigh << 32) + m_data.nFileSizeLow; + return ((int64_t) m_data.nFileSizeHigh << 32) + m_data.nFileSizeLow; #endif } @@ -84,7 +84,7 @@ ReFileSize_t ReDirStatus_t::fileSize() { * @return buffer.str() (for chaining) */ const char* ReDirStatus_t::filetimeAsString(ReByteBuffer& buffer) { - return filetimeToString(modified(), buffer); + return filetimeToString(modified(), buffer); } /** @@ -94,11 +94,12 @@ const char* ReDirStatus_t::filetimeAsString(ReByteBuffer& buffer) { * @param buffer OUT: the buffer for the string * @return buffer.str(), e.g. "2014.01.07 02:59:43" */ -const char* ReDirStatus_t::filetimeToString(const ReFileTime_t* time, ReByteBuffer& buffer){ - time_t time1 = filetimeToTime(time); - struct tm* time2 = localtime(&time1); - buffer.setLength(4+2*2+2*2+1+3*2+2*1); - strftime(buffer.buffer(), buffer.length(), "%Y.%m.%d %H:%M:%S", time2); +const char* ReDirStatus_t::filetimeToString(const ReFileTime_t* time, + ReByteBuffer& buffer) { + time_t time1 = filetimeToTime(time); + struct tm* time2 = localtime(&time1); + buffer.setLength(4 + 2 * 2 + 2 * 2 + 1 + 3 * 2 + 2 * 1); + strftime(buffer.buffer(), buffer.length(), "%Y.%m.%d %H:%M:%S", time2); return buffer.str(); } @@ -108,20 +109,20 @@ const char* ReDirStatus_t::filetimeToString(const ReFileTime_t* time, ReByteBuff * @param filetime the filetime to convert * @return the count of seconds since 1.1.1970 */ -time_t ReDirStatus_t::filetimeToTime(const ReFileTime_t* filetime){ +time_t ReDirStatus_t::filetimeToTime(const ReFileTime_t* filetime) { #ifdef __linux__ - return filetime->tv_sec; + return filetime->tv_sec; #elif defined __WIN32__ - // 64-bit arithmetic: - LARGE_INTEGER date, adjust; - date.HighPart = filetime->dwHighDateTime; - date.LowPart = filetime->dwLowDateTime; - // 100-nanoseconds = milliseconds * 10000 - adjust.QuadPart = 11644473600000 * 10000; - // removes the diff between 1970 and 1601 - date.QuadPart -= adjust.QuadPart; - // converts back from 100-nanoseconds to seconds - time_t rc = (time_t) (date.QuadPart / 10000000); + // 64-bit arithmetic: + LARGE_INTEGER date, adjust; + date.HighPart = filetime->dwHighDateTime; + date.LowPart = filetime->dwLowDateTime; + // 100-nanoseconds = milliseconds * 10000 + adjust.QuadPart = 11644473600000 * 10000; + // removes the diff between 1970 and 1601 + date.QuadPart -= adjust.QuadPart; + // converts back from 100-nanoseconds to seconds + time_t rc = (time_t) (date.QuadPart / 10000000); return rc; #endif } @@ -131,17 +132,17 @@ time_t ReDirStatus_t::filetimeToTime(const ReFileTime_t* filetime){ * * @return true: success */ -bool ReDirStatus_t::findFirst(){ +bool ReDirStatus_t::findFirst() { bool rc = false; #if defined __linux__ if (m_handle != NULL) - closedir(m_handle); + closedir(m_handle); m_handle = opendir(m_path.str()); rc = m_handle != NULL && (m_data = readdir(m_handle)) != NULL; m_status.st_ino = 0; #elif defined __WIN32__ if (m_handle != INVALID_HANDLE_VALUE) - FindClose(m_handle); + FindClose(m_handle); ReByteBuffer thePath(m_path); thePath.append(m_path.lastChar() == '\\' ? "*" : "\\*"); m_handle = FindFirstFileA(thePath.str(), &m_data); @@ -156,7 +157,7 @@ bool ReDirStatus_t::findFirst(){ * * @return true: success */ -bool ReDirStatus_t::findNext(){ +bool ReDirStatus_t::findNext() { #if defined __linux__ bool rc = m_handle != NULL && (m_data = readdir(m_handle)) != NULL; m_status.st_ino = 0; @@ -170,14 +171,14 @@ bool ReDirStatus_t::findNext(){ /** * Frees the resources of an instance. */ -void ReDirStatus_t::freeEntry(){ +void ReDirStatus_t::freeEntry() { #if defined __linux__ - if (m_handle != NULL){ + if (m_handle != NULL) { closedir(m_handle); m_handle = NULL; } #elif defined __WIN32__ - if (m_handle != INVALID_HANDLE_VALUE){ + if (m_handle != INVALID_HANDLE_VALUE) { FindClose(m_handle); m_handle = INVALID_HANDLE_VALUE; } @@ -191,7 +192,7 @@ void ReDirStatus_t::freeEntry(){ * * @return the filename with path */ -const char* ReDirStatus_t::fullName(){ +const char* ReDirStatus_t::fullName() { if (m_fullName.length() == 0) m_fullName.set(m_path).append(node(), -1); return m_fullName.str(); @@ -199,35 +200,35 @@ const char* ReDirStatus_t::fullName(){ #if defined __WIN32__ /** Gets the name of the file owner. -* -* @param handle file handle (see CreateFile()) -* @param name OUT: the owner: [domain\\]name -* @return true: success -*/ + * + * @param handle file handle (see CreateFile()) + * @param name OUT: the owner: [domain\\]name + * @return true: success + */ bool ReDirStatus_t::getFileOwner(HANDLE handle, const char* file, - ReByteBuffer& name, ReLogger* logger){ + ReByteBuffer& name, ReLogger* logger) { bool rc = false; PSID pSidOwner = NULL; PSECURITY_DESCRIPTOR pSD = NULL; if (GetSecurityInfo(handle, SE_FILE_OBJECT, - OWNER_SECURITY_INFORMATION, &pSidOwner, NULL, NULL, NULL, &pSD) != ERROR_SUCCESS) { + OWNER_SECURITY_INFORMATION, &pSidOwner, NULL, NULL, NULL, &pSD) != ERROR_SUCCESS) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_FILE_OWNER_1, - "GetSecurityInfo($1): $2").arg(file).arg((int) GetLastError()).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_FILE_OWNER_1, + "GetSecurityInfo($1): $2").arg(file).arg((int) GetLastError()).end(); } else { char accountName[128]; char domainName[128]; DWORD dwAcctName = sizeof accountName; DWORD dwDomainName = sizeof domainName; SID_NAME_USE eUse = SidTypeUnknown; - if (! LookupAccountSid(NULL, pSidOwner, accountName, &dwAcctName, domainName, - &dwDomainName, &eUse)){ + if (! LookupAccountSid(NULL, pSidOwner, accountName, &dwAcctName, domainName, + &dwDomainName, &eUse)) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_SECURITY, LC_GET_FILE_OWNER_2, - "LookupAccountSid(): $1").arg((int) GetLastError()).end(); + logger->sayF(LOG_ERROR | CAT_SECURITY, LC_GET_FILE_OWNER_2, + "LookupAccountSid(): $1").arg((int) GetLastError()).end(); } else { if (dwDomainName > 0) - name.append(domainName).appendChar('\\'); + name.append(domainName).appendChar('\\'); name.append(accountName); rc = true; } @@ -238,38 +239,38 @@ bool ReDirStatus_t::getFileOwner(HANDLE handle, const char* file, #if defined __WIN32__ /** Tries to get a privilege. -* -* @param privilege the name of the privilege, e.g. "SeBackup" -* @param logger logger for error logging -*/ -bool ReDirStatus_t::getPrivilege(const char* privilege, ReLogger* logger){ + * + * @param privilege the name of the privilege, e.g. "SeBackup" + * @param logger logger for error logging + */ +bool ReDirStatus_t::getPrivilege(const char* privilege, ReLogger* logger) { bool rc = false; LUID luidPrivilege; HANDLE hAccessToken; - if (! OpenProcessToken (GetCurrentProcess(), - TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hAccessToken)){ + if (! OpenProcessToken (GetCurrentProcess(), + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hAccessToken)) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_1, - "OpenProcessToken(): $1").arg((int) GetLastError()).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_1, + "OpenProcessToken(): $1").arg((int) GetLastError()).end(); } else if (! LookupPrivilegeValue (NULL, SE_BACKUP_NAME, &luidPrivilege)) { if (logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_2, - "LookupPrivilegeValue(): $1").arg((int) GetLastError()).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_2, + "LookupPrivilegeValue(): $1").arg((int) GetLastError()).end(); } else { - TOKEN_PRIVILEGES tpPrivileges; - tpPrivileges.PrivilegeCount = 1; - tpPrivileges.Privileges[0].Luid = luidPrivilege; - tpPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if (AdjustTokenPrivileges (hAccessToken, FALSE, &tpPrivileges, + TOKEN_PRIVILEGES tpPrivileges; + tpPrivileges.PrivilegeCount = 1; + tpPrivileges.Privileges[0].Luid = luidPrivilege; + tpPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + if (AdjustTokenPrivileges (hAccessToken, FALSE, &tpPrivileges, 0, NULL, NULL) == 0) - rc = true; + rc = true; else { int error = GetLastError(); if (error != 1300 && logger != NULL) - logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_3, - "AdjustTokenPrivileges(): $1").arg((int) GetLastError()).end(); + logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_3, + "AdjustTokenPrivileges(): $1").arg((int) GetLastError()).end(); } - } + } return rc; } #endif /* __WIN32__ */ @@ -281,10 +282,10 @@ bool ReDirStatus_t::getPrivilege(const char* privilege, ReLogger* logger){ */ bool ReDirStatus_t::isDirectory() { #ifdef __linux__ - return m_data->d_type == DT_DIR - || (m_data->d_type == DT_UNKNOWN && S_ISDIR(getStatus()->st_mode)); + return m_data->d_type == DT_DIR + || (m_data->d_type == DT_UNKNOWN && S_ISDIR(getStatus()->st_mode)); #elif defined __WIN32__ - return 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); + return 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); #endif } @@ -293,15 +294,15 @@ bool ReDirStatus_t::isDirectory() { * * @return true: an ignorable entry has been found */ -bool ReDirStatus_t::isDotDir() const{ +bool ReDirStatus_t::isDotDir() const { #ifdef __linux__ - bool rc = m_data == NULL || (m_data->d_name[0] == '.' && (m_data->d_name[1] == '\0' - || (m_data->d_name[1] == '.' && m_data->d_name[2] == '\0'))); + bool rc = m_data == NULL || (m_data->d_name[0] == '.' && (m_data->d_name[1] == '\0' + || (m_data->d_name[1] == '.' && m_data->d_name[2] == '\0'))); #elif defined __WIN32__ - bool rc = m_data.cFileName[0] == '.' && (m_data.cFileName[1] == '\0' - || (m_data.cFileName[1] == '.' && m_data.cFileName[2] == '\0')); + bool rc = m_data.cFileName[0] == '.' && (m_data.cFileName[1] == '\0' + || (m_data.cFileName[1] == '.' && m_data.cFileName[2] == '\0')); #endif - return rc; + return rc; } /** @@ -314,12 +315,12 @@ bool ReDirStatus_t::isDotDir() const{ bool ReDirStatus_t::isLink() { bool rc; #ifdef __linux__ - rc = m_data->d_type == DT_LNK - || (m_data->d_type == DT_UNKNOWN && S_ISLNK(getStatus()->st_mode)); + rc = m_data->d_type == DT_LNK + || (m_data->d_type == DT_UNKNOWN && S_ISLNK(getStatus()->st_mode)); #elif defined __WIN32__ - rc = 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT); + rc = 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT); #endif - return rc; + return rc; } /** * Tests whether the instance is a "normal" file. @@ -328,10 +329,10 @@ bool ReDirStatus_t::isLink() { */ bool ReDirStatus_t::isRegular() { #ifdef __linux__ - return m_data->d_type == DT_REG - || (m_data->d_type == DT_UNKNOWN && S_ISREG(getStatus()->st_mode)); + return m_data->d_type == DT_REG + || (m_data->d_type == DT_UNKNOWN && S_ISREG(getStatus()->st_mode)); #elif defined __WIN32__ - return 0 == (m_data.dwFileAttributes & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)); + return 0 == (m_data.dwFileAttributes & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)); #endif } /** @@ -341,9 +342,9 @@ bool ReDirStatus_t::isRegular() { */ const ReFileTime_t* ReDirStatus_t::modified() { #ifdef __linux__ - return &(getStatus()->st_mtim); + return &(getStatus()->st_mtim); #elif defined __WIN32__ - return &m_data.ftLastWriteTime; + return &m_data.ftLastWriteTime; #endif } @@ -352,45 +353,45 @@ const ReFileTime_t* ReDirStatus_t::modified() { * * @return the name of the current file. */ -const char* ReDirStatus_t::node() const{ +const char* ReDirStatus_t::node() const { #ifdef __linux__ - return m_data->d_name; + return m_data->d_name; #elif defined __WIN32__ - return m_data.cFileName; + return m_data.cFileName; #endif } -inline void addRight(int mode, ReByteBuffer& buffer){ +inline void addRight(int mode, ReByteBuffer& buffer) { char right; - switch(mode & 7){ - case 1: - right = 'x'; - break; - case 2: - right = 'w'; - break; - case 3: - right = 'X'; - break; - case 4: - right = 'r'; - break; - case 5: - right = 'R'; - break; - case 6: - right = 'W'; - break; - case 7: - right = 'A'; - break; - default: - right = '-'; - break; + switch (mode & 7) { + case 1: + right = 'x'; + break; + case 2: + right = 'w'; + break; + case 3: + right = 'X'; + break; + case 4: + right = 'r'; + break; + case 5: + right = 'R'; + break; + case 6: + right = 'W'; + break; + case 7: + right = 'A'; + break; + default: + right = '-'; + break; } buffer.appendChar(right); } -inline void addId(const char* id, int maxLength, ReByteBuffer& buffer){ +inline void addId(const char* id, int maxLength, ReByteBuffer& buffer) { int length = strlen(id); if (length == maxLength) buffer.append(id, length); @@ -409,11 +410,11 @@ inline void addId(const char* id, int maxLength, ReByteBuffer& buffer){ * @param ownerWidth the width for group/owner * @return buffer.str() (for chaining) */ -const char* ReDirStatus_t::rightsAsString(ReByteBuffer& buffer, bool numerical, - int ownerWidth) { - buffer.setLength(0); +const char* ReDirStatus_t::rightsAsString(ReByteBuffer& buffer, bool numerical, + int ownerWidth) { + buffer.setLength(0); #if defined __linux__ - if (numerical){ + if (numerical) { buffer.appendInt(getStatus()->st_mode & ALLPERMS, "%04o"); buffer.appendInt(getStatus()->st_uid, " %4d"); buffer.appendInt(getStatus()->st_gid, " %4d"); @@ -425,43 +426,43 @@ const char* ReDirStatus_t::rightsAsString(ReByteBuffer& buffer, bool numerical, buffer.appendChar(' '); struct passwd* passwd = getpwuid(getStatus()->st_uid); if (passwd == NULL) - buffer.appendInt(getStatus()->st_uid, "%4d"); + buffer.appendInt(getStatus()->st_uid, "%4d"); else - addId(passwd->pw_name, 5, buffer); + addId(passwd->pw_name, 5, buffer); buffer.appendChar(' '); struct group* group = getgrgid(getStatus()->st_gid); if (group == NULL) - buffer.appendInt(getStatus()->st_gid, "%4d"); + buffer.appendInt(getStatus()->st_gid, "%4d"); else - addId(group->gr_name, 5, buffer); + addId(group->gr_name, 5, buffer); buffer.appendChar(' '); } #elif defined __WIN32__ const char* name = fullName(); HANDLE handle = INVALID_HANDLE_VALUE; - if (! isDirectory()){ + if (! isDirectory()) { if ( (handle = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) - m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_1, - "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end(); - } else if (m_getPrivilege){ + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) + m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_1, + "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end(); + } else if (m_getPrivilege) { // we try only one time: m_getPrivilege = false; - if (getPrivilege(SE_BACKUP_NAME, m_logger)){ - if ( (handle = CreateFile(name, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, - NULL)) != INVALID_HANDLE_VALUE) - m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_2, - "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end(); + if (getPrivilege(SE_BACKUP_NAME, m_logger)) { + if ( (handle = CreateFile(name, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, + NULL)) != INVALID_HANDLE_VALUE) + m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_2, + "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end(); } } ReByteBuffer owner; if (handle != INVALID_HANDLE_VALUE) - getFileOwner(handle, name, owner, m_logger); + getFileOwner(handle, name, owner, m_logger); CloseHandle(handle); buffer.appendFix(owner.str(), owner.length(), ownerWidth, ownerWidth); #endif - return buffer.str(); + return buffer.str(); } /** @@ -470,64 +471,64 @@ const char* ReDirStatus_t::rightsAsString(ReByteBuffer& buffer, bool numerical, * @param time the unix time (secondes since 1.1.1970) * @param filetime OUT: the OS specific filetime */ -void ReDirStatus_t::timeToFiletime(time_t time, ReFileTime_t& filetime){ +void ReDirStatus_t::timeToFiletime(time_t time, ReFileTime_t& filetime) { #ifdef __linux__ - filetime.tv_sec = time; + filetime.tv_sec = time; filetime.tv_nsec = 0; #elif defined __WIN32__ - LONGLONG ll = Int32x32To64(time, 10000000) + 116444736000000000; - filetime.dwLowDateTime = (DWORD)ll; - filetime.dwHighDateTime = ll >> 32; + LONGLONG ll = Int32x32To64(time, 10000000) + 116444736000000000; + filetime.dwLowDateTime = (DWORD)ll; + filetime.dwHighDateTime = ll >> 32; #endif } /** * Returns the type of the entry. * return the file type, e.g. TF_REGULAR */ -ReDirStatus_t::Type_t ReDirStatus_t::type(){ - Type_t rc = TF_UNDEF; +ReDirStatus_t::Type_t ReDirStatus_t::type() { + Type_t rc = TF_UNDEF; #if defined __linux__ int flags = getStatus()->st_mode; - if (S_ISDIR(flags)) - rc = TF_SUBDIR; - else if (flags == 0 || S_ISREG(flags)) - rc = TF_REGULAR; - else if (S_ISLNK(flags)) - rc = TF_LINK; - else if (S_ISCHR(flags)) - rc = TF_CHAR; - else if (S_ISBLK(flags)) - rc = TF_BLOCK; - else if (S_ISFIFO(flags)) - rc = TF_PIPE; - else if (S_ISSOCK(flags)) - rc = TF_SOCKET; - else - rc = TF_OTHER; + if (S_ISDIR(flags)) + rc = TF_SUBDIR; + else if (flags == 0 || S_ISREG(flags)) + rc = TF_REGULAR; + else if (S_ISLNK(flags)) + rc = TF_LINK; + else if (S_ISCHR(flags)) + rc = TF_CHAR; + else if (S_ISBLK(flags)) + rc = TF_BLOCK; + else if (S_ISFIFO(flags)) + rc = TF_PIPE; + else if (S_ISSOCK(flags)) + rc = TF_SOCKET; + else + rc = TF_OTHER; #elif defined __WIN32__ - int flags = (m_data.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY - | FILE_ATTRIBUTE_HIDDEN - | FILE_ATTRIBUTE_SYSTEM - | FILE_ATTRIBUTE_ARCHIVE - | FILE_ATTRIBUTE_NORMAL - | FILE_ATTRIBUTE_TEMPORARY - | FILE_ATTRIBUTE_SPARSE_FILE - | FILE_ATTRIBUTE_COMPRESSED - | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED - | FILE_ATTRIBUTE_ENCRYPTED - | FILE_ATTRIBUTE_HIDDEN)); - - if (0 == flags) - rc = TF_REGULAR; - else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){ - rc = (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) - ? TF_LINK_DIR : TF_SUBDIR; - } else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) - rc = TF_LINK; - else - rc = TF_OTHER; + int flags = (m_data.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY + | FILE_ATTRIBUTE_HIDDEN + | FILE_ATTRIBUTE_SYSTEM + | FILE_ATTRIBUTE_ARCHIVE + | FILE_ATTRIBUTE_NORMAL + | FILE_ATTRIBUTE_TEMPORARY + | FILE_ATTRIBUTE_SPARSE_FILE + | FILE_ATTRIBUTE_COMPRESSED + | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED + | FILE_ATTRIBUTE_ENCRYPTED + | FILE_ATTRIBUTE_HIDDEN)); + + if (0 == flags) + rc = TF_REGULAR; + else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + rc = (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) + ? TF_LINK_DIR : TF_SUBDIR; + } else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) + rc = TF_LINK; + else + rc = TF_OTHER; #endif - return rc; + return rc; } /** @@ -535,33 +536,33 @@ ReDirStatus_t::Type_t ReDirStatus_t::type(){ * * @return the filetype, e.g. 'd' for a directory */ -char ReDirStatus_t::typeAsChar(){ +char ReDirStatus_t::typeAsChar() { char rc = ' '; - switch(type()){ - case TF_REGULAR: - rc = ' '; - break; - case TF_LINK: - rc = 'l'; - break; - case TF_SUBDIR: - rc = 'd'; - break; - case TF_CHAR: - rc = 'c'; - break; - case TF_BLOCK: - rc = 'b'; - break; - case TF_PIPE: - rc = 'p'; - break; - case TF_SOCKET: - rc = 's'; - break; - default: - rc = 'o'; - break; + switch (type()) { + case TF_REGULAR: + rc = ' '; + break; + case TF_LINK: + rc = 'l'; + break; + case TF_SUBDIR: + rc = 'd'; + break; + case TF_CHAR: + rc = 'c'; + break; + case TF_BLOCK: + rc = 'b'; + break; + case TF_PIPE: + rc = 'p'; + break; + case TF_SOCKET: + rc = 's'; + break; + default: + rc = 'o'; + break; } return rc; } @@ -569,16 +570,15 @@ char ReDirStatus_t::typeAsChar(){ * Constructor. */ ReDirEntryFilter_t::ReDirEntryFilter_t() : - m_types(ReDirStatus_t::TC_ALL), - m_nodePatterns(NULL), - m_pathPatterns(NULL), - m_minSize(0), - m_maxSize(-1), - //m_minAge(0), - //m_maxAge(0), - m_minDepth(0), - m_maxDepth(512) -{ + m_types(ReDirStatus_t::TC_ALL), + m_nodePatterns(NULL), + m_pathPatterns(NULL), + m_minSize(0), + m_maxSize(-1), + //m_minAge(0), + //m_maxAge(0), + m_minDepth(0), + m_maxDepth(512) { setFiletimeUndef(m_minAge); setFiletimeUndef(m_maxAge); } @@ -586,32 +586,33 @@ ReDirEntryFilter_t::ReDirEntryFilter_t() : /** * Destructor. */ -ReDirEntryFilter_t::~ReDirEntryFilter_t(){ +ReDirEntryFilter_t::~ReDirEntryFilter_t() { } /** * */ -bool ReDirEntryFilter_t::match(ReDirStatus_t& entry){ +bool ReDirEntryFilter_t::match(ReDirStatus_t& entry) { bool rc = false; do { if (0 == (entry.type() & m_types)) break; - int64_t size = entry.fileSize(); - if (m_minSize > 0 && size < m_minSize) + int64_t size = entry.fileSize(); + if (m_minSize > 0 && size < m_minSize) break; if (m_maxSize >= 0 && size > m_maxSize) break; - if (! filetimeIsUndefined(m_minAge) && *entry.modified() > m_minAge) + if (!filetimeIsUndefined(m_minAge) && *entry.modified() > m_minAge) break; - if (! filetimeIsUndefined(m_maxAge) && m_maxAge > *entry.modified()) + if (!filetimeIsUndefined(m_maxAge) && m_maxAge > *entry.modified()) break; const char* node = entry.node(); - if (m_nodePatterns != NULL && ! m_nodePatterns->match(node)) + if (m_nodePatterns != NULL && !m_nodePatterns->match(node)) break; rc = true; - } while(false); + } while (false); return rc; -}; +} +; #ifdef __linux__ /** @@ -620,9 +621,9 @@ bool ReDirEntryFilter_t::match(ReDirStatus_t& entry){ * @return the status of the current file */ struct stat* ReDirStatus_t::getStatus() { - if (m_status.st_ino == 0){ + if (m_status.st_ino == 0) { if (stat(fullName(), &m_status) != 0) - m_status.st_ino = 0; + m_status.st_ino = 0; } return &m_status; } @@ -632,10 +633,9 @@ struct stat* ReDirStatus_t::getStatus() { * Constructor. */ ReDirTreeStatistic::ReDirTreeStatistic() : - m_directories(0), - m_files(0), - m_sizes(0ll) -{ + m_directories(0), + m_files(0), + m_sizes(0ll) { } /** * Builds a string describing the data. @@ -648,10 +648,10 @@ ReDirTreeStatistic::ReDirTreeStatistic() : * @param formatFiles the sprintf format for the directory count, e.g. "%6d" * @return a human readable string */ -const char* ReDirTreeStatistic::statisticAsString(ReByteBuffer& buffer, bool append, - const char* formatFiles, const char* formatSizes, const char* formatDirs) -{ - if (! append) +const char* ReDirTreeStatistic::statisticAsString(ReByteBuffer& buffer, + bool append, const char* formatFiles, const char* formatSizes, + const char* formatDirs) { + if (!append) buffer.setLength(0); buffer.appendInt(m_files, formatFiles); buffer.append(i18n("file(s)")).appendChar(' '); @@ -663,24 +663,23 @@ const char* ReDirTreeStatistic::statisticAsString(ReByteBuffer& buffer, bool app } /** -* Constructor. -* -* @param triggerCount efficiency: only every N calls a time check takes place -* @param interval the minimum number of seconds between two traces -*/ + * Constructor. + * + * @param triggerCount efficiency: only every N calls a time check takes place + * @param interval the minimum number of seconds between two traces + */ ReTraceUnit::ReTraceUnit(int triggerCount, int interval) : - m_count(0), - m_triggerCount(triggerCount), - m_lastTrace(0), - m_interval(interval), - m_startTime(time(NULL)) -{ + m_count(0), + m_triggerCount(triggerCount), + m_lastTrace(0), + m_interval(interval), + m_startTime(time(NULL)) { m_lastTrace = m_startTime; } /** * Destructor. */ -ReTraceUnit::~ReTraceUnit(){ +ReTraceUnit::~ReTraceUnit() { } /** @@ -691,7 +690,7 @@ ReTraceUnit::~ReTraceUnit(){ * @param message message for the trace * @return true (for chaining) */ -bool ReTraceUnit::trace(const char* message){ +bool ReTraceUnit::trace(const char* message) { printf("%d\n", message); return true; } @@ -701,22 +700,23 @@ bool ReTraceUnit::trace(const char* message){ * * @param base the base directory. The traversal starts at this point */ -ReTraverser::ReTraverser(const char* base, ReTraceUnit* tracer, ReLogger* logger) : - ReDirTreeStatistic(), - m_minLevel(0), - m_maxLevel(512), - m_level(-1), - m_base(base), - // m_dirs - m_passNoForDirSearch(2), - m_dirPatterns(NULL), - m_tracer(tracer), - m_logger(logger) -{ +ReTraverser::ReTraverser(const char* base, ReTraceUnit* tracer, + ReLogger* logger) : + ReDirTreeStatistic(), + m_minLevel(0), + m_maxLevel(512), + m_level(-1), + m_base(base), + // m_dirs + m_passNoForDirSearch(2), + m_dirPatterns(NULL), + m_tracer(tracer), + m_logger(logger) { memset(m_dirs, 0, sizeof m_dirs); m_dirs[0] = new ReDirStatus_t(m_logger); // remove a preceeding "./". This simplifies the pattern expressions: - if (m_base.startsWith(ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())){ + if (m_base.startsWith( + ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())) { m_base.remove(0, 2); } } @@ -733,13 +733,14 @@ ReTraverser::~ReTraverser() { * * @param base the base directory to search */ -void ReTraverser::changeBase(const char* base){ +void ReTraverser::changeBase(const char* base) { destroy(); m_base.setLength(0).append(base); memset(m_dirs, 0, sizeof m_dirs); m_dirs[0] = new ReDirStatus_t(m_logger); // remove a preceeding "./". This simplifies the pattern expressions: - if (m_base.startsWith(ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())){ + if (m_base.startsWith( + ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())) { m_base.remove(0, 2); } } @@ -748,8 +749,8 @@ void ReTraverser::changeBase(const char* base){ * Releases the resources. */ void ReTraverser::destroy() { - for (size_t ix = 0; ix < sizeof m_dirs / sizeof m_dirs[0]; ix++){ - if (m_dirs[ix] != NULL){ + for (size_t ix = 0; ix < sizeof m_dirs / sizeof m_dirs[0]; ix++) { + if (m_dirs[ix] != NULL) { m_dirs[ix]->freeEntry(); delete m_dirs[ix]; m_dirs[ix] = NULL; @@ -766,53 +767,53 @@ void ReTraverser::destroy() { * otherwise: the stack entry with the next file in the * directory tree. May be a directory too */ -ReDirStatus_t* ReTraverser::rawNextFile(int& level) -{ +ReDirStatus_t* ReTraverser::rawNextFile(int& level) { ReDirStatus_t* rc = NULL; bool alreadyRead = false; bool again; - do{ - again = false; - if (m_level < 0){ + do { + again = false; + if (m_level < 0) { // Not yet initialized? if (m_dirs[0]->m_passNo == 2) rc = NULL; else { // first call: - if (initEntry(m_base.str(), NULL, 0)){ + if (initEntry(m_base.str(), NULL, 0)) { m_directories++; if (1 != m_passNoForDirSearch) - rc = m_dirs[0]; + rc = m_dirs[0]; else again = alreadyRead = true; } } } else { ReDirStatus_t* current = m_dirs[m_level]; - if (alreadyRead || current->findNext()){ + if (alreadyRead || current->findNext()) { alreadyRead = false; // a file or directory found: - if (m_tracer != NULL && m_tracer->isCountTriggered() - && m_tracer->isTimeTriggered()) + if (m_tracer != NULL && m_tracer->isCountTriggered() + && m_tracer->isTimeTriggered()) m_tracer->trace(current->fullName()); - if (current->m_passNo != m_passNoForDirSearch){ + if (current->m_passNo != m_passNoForDirSearch) { // we search for any file: rc = m_dirs[m_level]; } else { // we are interested only in true subdirectories: again = true; - if (m_level < m_maxLevel && current->isDirectory() - && ! current->isDotDir() && ! current->isLink() - && (m_dirPatterns == NULL - || isAllowedDir(current->node()))){ + if (m_level < m_maxLevel && current->isDirectory() + && !current->isDotDir() && !current->isLink() + && (m_dirPatterns == NULL + || isAllowedDir(current->node()))) { // open a new level - alreadyRead = initEntry(current->m_path, current->node() , m_level + 1); + alreadyRead = initEntry(current->m_path, + current->node(), m_level + 1); m_directories++; } } } else { // the current subdir does not have more files: - if (current->m_passNo == 1){ + if (current->m_passNo == 1) { // we start the second pass: alreadyRead = initEntry(current->m_path, NULL, -1); current->m_passNo = 2; @@ -820,7 +821,7 @@ ReDirStatus_t* ReTraverser::rawNextFile(int& level) } else { // this subdirectory is complete. We continue in the parent directory: current->freeEntry(); - if ( --m_level >= 0){ + if (--m_level >= 0) { again = true; } } @@ -828,8 +829,8 @@ ReDirStatus_t* ReTraverser::rawNextFile(int& level) } if (rc != NULL && rc->isDotDir()) again = true; - } while(again); - if (rc != NULL && ! rc->isDirectory()){ + } while (again); + if (rc != NULL && !rc->isDirectory()) { m_files++; if (m_sizes >= 0) m_sizes += rc->fileSize(); @@ -849,10 +850,10 @@ ReDirStatus_t* ReTraverser::rawNextFile(int& level) * otherwise: the info about the next file in the * directory tree */ -ReDirStatus_t* ReTraverser::nextFile(int& level, ReDirEntryFilter_t* filter){ +ReDirStatus_t* ReTraverser::nextFile(int& level, ReDirEntryFilter_t* filter) { ReDirStatus_t* rc = rawNextFile(level); - while (rc != NULL){ - if (filter == NULL || filter->match(*rc)){ + while (rc != NULL) { + if (filter == NULL || filter->match(*rc)) { break; } rc = rawNextFile(level); @@ -870,25 +871,26 @@ ReDirStatus_t* ReTraverser::nextFile(int& level, ReDirEntryFilter_t* filter){ * @return true: a new file is available
* false/code>: findFirstEntry() signals: no entry. */ -bool ReTraverser::initEntry(const ReByteBuffer& parent, const char* node, int level){ - bool rc = false; - if (level < MAX_ENTRY_STACK_DEPTH){ - if (level >= 0) - m_level = level; +bool ReTraverser::initEntry(const ReByteBuffer& parent, const char* node, + int level) { + bool rc = false; + if (level < MAX_ENTRY_STACK_DEPTH) { + if (level >= 0) + m_level = level; if (m_dirs[m_level] == NULL) m_dirs[m_level] = new ReDirStatus_t(m_logger); ReDirStatus_t* current = m_dirs[m_level]; - current->m_passNo = 1; - if (level >= 0){ - current->m_path.set(parent.str(), parent.length()); - if (! parent.endsWith(OS_SEPARATOR)) - current->m_path.append(OS_SEPARATOR); - if (node != NULL) - current->m_path.append(node).append(OS_SEPARATOR); - } - rc = current->findFirst(); + current->m_passNo = 1; + if (level >= 0) { + current->m_path.set(parent.str(), parent.length()); + if (!parent.endsWith(OS_SEPARATOR)) + current->m_path.append(OS_SEPARATOR); + if (node != NULL) + current->m_path.append(node).append(OS_SEPARATOR); + } + rc = current->findFirst(); } - return rc; + return rc; } /** @@ -896,7 +898,7 @@ bool ReTraverser::initEntry(const ReByteBuffer& parent, const char* node, int le * * @param filter the filter with the properties to set */ -void ReTraverser::setPropertiesFromFilter(ReDirEntryFilter_t* filter){ +void ReTraverser::setPropertiesFromFilter(ReDirEntryFilter_t* filter) { m_minLevel = filter->m_minDepth; m_maxLevel = filter->m_maxDepth; setDirPattern(filter->m_pathPatterns); @@ -911,7 +913,7 @@ void ReTraverser::setPropertiesFromFilter(ReDirEntryFilter_t* filter){ * @return NULL: not available
* otherwise: the wanted entry */ -ReDirStatus_t* ReTraverser::topOfStack(int offsetFromTop){ +ReDirStatus_t* ReTraverser::topOfStack(int offsetFromTop) { ReDirStatus_t* rc = NULL; if (offsetFromTop >= 0 && m_level - 1 - offsetFromTop >= 0) rc = m_dirs[m_level - 1 - offsetFromTop]; diff --git a/os/ReTraverser.hpp b/os/ReTraverser.hpp index 79885b6..75ddb62 100644 --- a/os/ReTraverser.hpp +++ b/os/ReTraverser.hpp @@ -21,7 +21,7 @@ typedef DIR* FindFileHandle_t; * @param time the filetime to test * @return true: the given filetime is undefined */ -inline bool filetimeIsUndefined(ReFileTime_t& time){ +inline bool filetimeIsUndefined(ReFileTime_t& time) { #if defined __linux__ return time.tv_sec == 0 && time.tv_nsec == 0; #elif defined __WIN32__ @@ -31,62 +31,64 @@ inline bool filetimeIsUndefined(ReFileTime_t& time){ /** Sets the filetime to undefined. * @param time the filetime to clear */ -inline void setFiletimeUndef(ReFileTime_t& time){ +inline void setFiletimeUndef(ReFileTime_t& time) { #if defined __linux__ time.tv_sec = time.tv_nsec = 0; #elif defined __WIN32__ - time.dwHighDateTime = time.dwLowDateTime = 0; + time.dwHighDateTime = time.dwLowDateTime = 0; #endif } -class ReDirStatus_t{ +class ReDirStatus_t { public: - enum Type_t { - TF_UNDEF = 0, - // single property flags: - TF_SUBDIR = 1 << 0, - TF_REGULAR = 1 << 1, - TF_LINK = 1 << 2, - TF_LINK_DIR = 1 << 3, - TF_BLOCK = 1 << 4, - TF_PIPE = 1 << 5, - TF_CHAR = 1 << 6, - TF_SOCKET = 1 << 7, - TF_OTHER = 1 << 8, - // collections: - TC_SPECIAL = (TF_BLOCK | TF_CHAR | TF_SOCKET | TF_PIPE | TF_OTHER), - TC_NON_DIR = (TC_SPECIAL | TF_LINK | TF_REGULAR), - TC_ALL = (TF_SUBDIR | TC_NON_DIR | TF_LINK_DIR) - }; + enum Type_t { + TF_UNDEF = 0, + // single property flags: + TF_SUBDIR = 1 << 0, + TF_REGULAR = 1 << 1, + TF_LINK = 1 << 2, + TF_LINK_DIR = 1 << 3, + TF_BLOCK = 1 << 4, + TF_PIPE = 1 << 5, + TF_CHAR = 1 << 6, + TF_SOCKET = 1 << 7, + TF_OTHER = 1 << 8, + // collections: + TC_SPECIAL = (TF_BLOCK | TF_CHAR | TF_SOCKET | TF_PIPE | TF_OTHER), + TC_NON_DIR = (TC_SPECIAL | TF_LINK | TF_REGULAR), + TC_ALL = (TF_SUBDIR | TC_NON_DIR | TF_LINK_DIR) + }; public: ReDirStatus_t(ReLogger* logger); public: - const ReFileTime_t* accessed(); - ReFileSize_t fileSize(); - const char* filetimeAsString(ReByteBuffer& buffer); - bool findFirst(); - bool findNext(); + const ReFileTime_t* accessed(); + ReFileSize_t fileSize(); + const char* filetimeAsString(ReByteBuffer& buffer); + bool findFirst(); + bool findNext(); void freeEntry(); const char* fullName(); - bool isDirectory(); - bool isDotDir() const; - bool isLink(); - bool isRegular(); - const ReFileTime_t* modified(); - const char* node() const; - const char* rightsAsString(ReByteBuffer& buffer, bool numerical, int ownerWidth); - Type_t type(); + bool isDirectory(); + bool isDotDir() const; + bool isLink(); + bool isRegular(); + const ReFileTime_t* modified(); + const char* node() const; + const char* rightsAsString(ReByteBuffer& buffer, bool numerical, + int ownerWidth); + Type_t type(); char typeAsChar(); public: - static const char* filetimeToString(const ReFileTime_t* time, ReByteBuffer& buffer); - static time_t filetimeToTime(const ReFileTime_t* time); + static const char* filetimeToString(const ReFileTime_t* time, + ReByteBuffer& buffer); + static time_t filetimeToTime(const ReFileTime_t* time); #if defined __WIN32__ static bool getFileOwner(HANDLE handle, const char* file, ReByteBuffer& name, ReLogger* logger = NULL); static bool getPrivilege(const char* privilege, ReLogger* logger); #endif - static void timeToFiletime(time_t time, ReFileTime_t& filetime); + static void timeToFiletime(time_t time, ReFileTime_t& filetime); public: ReByteBuffer m_path; ReByteBuffer m_fullName; @@ -104,7 +106,7 @@ public: bool m_getPrivilege; #endif }; -class ReDirEntryFilter_t{ +class ReDirEntryFilter_t { public: ReDirEntryFilter_t(); ~ReDirEntryFilter_t(); @@ -118,10 +120,10 @@ public: ReFileSize_t m_maxSize; ReFileTime_t m_minAge; ReFileTime_t m_maxAge; - int m_minDepth; - int m_maxDepth; + int m_minDepth; + int m_maxDepth; }; -class ReTraceUnit{ +class ReTraceUnit { public: ReTraceUnit(int m_triggerCount = 10, int interval = 60); virtual ~ReTraceUnit(); @@ -130,8 +132,8 @@ public: * To avoid too the not cheap call of time() the trace unit uses a counter. * If the counter reaches a given level the time check should be done. * @return true: the counter has reached m_triggerCount - */ - inline bool isCountTriggered(){ + */ + inline bool isCountTriggered() { bool rc = ++m_count % m_triggerCount == 0; return rc; } @@ -139,16 +141,16 @@ public: * @return true: the last trace has been done after * at least m_interval seconds */ - inline bool isTimeTriggered(){ + inline bool isTimeTriggered() { time_t now = time(NULL); bool rc = now - m_lastTrace > m_interval; - if (rc){ + if (rc) { m_lastTrace = now; } return rc; } virtual bool trace(const char* message); -protected: +protected: int m_count; int m_triggerCount; time_t m_lastTrace; @@ -161,12 +163,12 @@ public: ReDirTreeStatistic(); public: const char* statisticAsString(ReByteBuffer& buffer, bool append = false, - const char* formatFiles = "%8d ", const char* formatSizes = "%12.6f", - const char* formatDirs = "%7d "); + const char* formatFiles = "%8d ", const char* formatSizes = "%12.6f", + const char* formatDirs = "%7d "); /** * Resets the counters. */ - inline void clear(){ + inline void clear() { m_files = m_directories = 0; m_sizes = 0ll; } @@ -176,11 +178,11 @@ public: int64_t m_sizes; }; - #define MAX_ENTRY_STACK_DEPTH 256 -class ReTraverser : public ReDirTreeStatistic { +class ReTraverser: public ReDirTreeStatistic { public: - ReTraverser(const char* base, ReTraceUnit* tracer = NULL, ReLogger* logger = NULL); + ReTraverser(const char* base, ReTraceUnit* tracer = NULL, ReLogger* logger = + NULL); virtual ~ReTraverser(); public: void changeBase(const char* base); @@ -200,25 +202,27 @@ public: } ReDirStatus_t* rawNextFile(int& level); ReDirStatus_t* nextFile(int& level, ReDirEntryFilter_t* filter = NULL); - /** Sets directory filter (pattern list). - * @param pattern pattern list for the subdirs to be entered - */ - void setDirPattern(RePatternList* pattern) - { m_dirPatterns = pattern; + /** Sets directory filter (pattern list). + * @param pattern pattern list for the subdirs to be entered + */ + void setDirPattern(RePatternList* pattern) { + m_dirPatterns = pattern; if (pattern != NULL) m_dirPatterns->setIgnoreCase(true); } - /** Sets the maximal depth. - * @param value the value to set - */ - void setMaxLevel(int value) - { m_maxLevel = value; } - /** Sets the minimal depth. - * @param value the value to set - */ - void setMinLevel(int value) - { m_minLevel = value; } - void setPropertiesFromFilter(ReDirEntryFilter_t* filter); + /** Sets the maximal depth. + * @param value the value to set + */ + void setMaxLevel(int value) { + m_maxLevel = value; + } + /** Sets the minimal depth. + * @param value the value to set + */ + void setMinLevel(int value) { + m_minLevel = value; + } + void setPropertiesFromFilter(ReDirEntryFilter_t* filter); /** * Return the sum of file lengths of the found files. * @return the sum of file lengths of the files found until now @@ -232,18 +236,18 @@ protected: void freeEntry(int level); bool initEntry(const ReByteBuffer& parent, const char* node, int level); /** - * Tests whether a directory should be processed. - * @param node the base name of the subdir - * @return true: the subdir will be processed
- * false: do not enter this subdir - */ - inline bool isAllowedDir(const char* node){ + * Tests whether a directory should be processed. + * @param node the base name of the subdir + * @return true: the subdir will be processed
+ * false: do not enter this subdir + */ + inline bool isAllowedDir(const char* node) { bool rc = m_dirPatterns->match(node); return rc; } protected: - int m_minLevel; - int m_maxLevel; + int m_minLevel; + int m_maxLevel; int m_level; ReByteBuffer m_base; ReDirStatus_t* m_dirs[MAX_ENTRY_STACK_DEPTH]; diff --git a/os/reos.hpp b/os/reos.hpp index 0b1dbb2..68f63c7 100644 --- a/os/reos.hpp +++ b/os/reos.hpp @@ -28,13 +28,13 @@ * @param time2 second operand * @return true: time1 > time2 */ -inline bool operator >(const ReFileTime_t& time1, const ReFileTime_t& time2){ +inline bool operator >(const ReFileTime_t& time1, const ReFileTime_t& time2) { #if defined __linux__ return time1.tv_sec > time2.tv_sec || time1.tv_sec == time2.tv_sec && time1.tv_nsec > time2.tv_nsec; #else return time1.dwHighDateTime > time2.dwHighDateTime - || time1.dwHighDateTime == time2.dwHighDateTime - && time1.dwLowDateTime > time2.dwLowDateTime; + || time1.dwHighDateTime == time2.dwHighDateTime + && time1.dwLowDateTime > time2.dwLowDateTime; #endif } #include "os/ReTraverser.hpp" diff --git a/string/ReMatcher.cpp b/string/ReMatcher.cpp index e2b4940..0e91816 100644 --- a/string/ReMatcher.cpp +++ b/string/ReMatcher.cpp @@ -20,10 +20,9 @@ extern void* memset (void *s, int c, size_t n); * Constructor. */ ReMatcher::ReMatcher() : - m_findAll(false), - m_ignoreCase(true), - m_notPattern(false) -{ + m_findAll(false), + m_ignoreCase(true), + m_notPattern(false) { } /** @@ -36,29 +35,26 @@ ReMatcher::~ReMatcher() { * Constructor. */ ReSimpleMatcher::ReSimpleMatcher() : - ReMatcher(), - m_pattern(), - m_tokens() -{ + ReMatcher(), + m_pattern(), + m_tokens() { } - /** * Constructor. * * @param pattern the search pattern */ ReSimpleMatcher::ReSimpleMatcher(const char* pattern) : - ReMatcher(), - m_pattern(), - m_tokens() -{ + ReMatcher(), + m_pattern(), + m_tokens() { compile(pattern); } /** * Destructor. */ -ReSimpleMatcher::~ReSimpleMatcher(){ +ReSimpleMatcher::~ReSimpleMatcher() { } /** @@ -68,10 +64,10 @@ ReSimpleMatcher::~ReSimpleMatcher(){ * @return true: success
* false: error occurred */ -bool ReSimpleMatcher::compile(const char* pattern){ +bool ReSimpleMatcher::compile(const char* pattern) { bool rc = true; m_pattern.set(pattern, -1); - if (pattern[0] == '*' && pattern[1] == '\0'){ + if (pattern[0] == '*' && pattern[1] == '\0') { m_findAll = true; } else { m_tokens.split(pattern, '*'); @@ -85,12 +81,12 @@ bool ReSimpleMatcher::compile(const char* pattern){ * @param fp target file pointer * @param prefix NULL or a introduction */ -void ReSimpleMatcher::dump(FILE* fp, const char* prefix) const{ +void ReSimpleMatcher::dump(FILE* fp, const char* prefix) const { ReByteBuffer buffer; if (prefix != NULL) fprintf(fp, "%s\n", prefix); fprintf(fp, "pattern: %s token (%d): %s\n", m_pattern.str(), - m_tokens.count(), m_tokens.join(" ", buffer).str()); + m_tokens.count(), m_tokens.join(" ", buffer).str()); } /** @@ -103,37 +99,39 @@ void ReSimpleMatcher::dump(FILE* fp, const char* prefix) const{ * m_notPattern: the name matches not
* false: otherwise */ -bool ReSimpleMatcher::match(const ReByteBuffer& toTest, ReHit* hit) const{ +bool ReSimpleMatcher::match(const ReByteBuffer& toTest, ReHit* hit) const { bool rc = m_findAll; - if (! rc){ + if (!rc) { do { size_t length0 = m_tokens.strLengthOf(0); // Does the anchor match? - if (length0 > 0 && ! toTest.startsWith(m_tokens.strOf(0), length0, - m_ignoreCase)){ - break; + if (length0 > 0 + && !toTest.startsWith(m_tokens.strOf(0), length0, + m_ignoreCase)) { + break; } // Does the tail match? int last = m_tokens.count() - 1; - if (last == 0){ + if (last == 0) { rc = true; break; } size_t lengthLast = m_tokens.strLengthOf(last); - if (lengthLast > 0 && ! toTest.endsWith(m_tokens.strOf(last), - lengthLast, m_ignoreCase)){ + if (lengthLast > 0 + && !toTest.endsWith(m_tokens.strOf(last), lengthLast, + m_ignoreCase)) { break; } // only anchor and tail? - if (last == 1){ + if (last == 1) { rc = true; break; } rc = searchTokens(toTest, 1, last - 1, hit, false); - } while(false); + } while (false); } if (m_notPattern) - rc = ! rc; + rc = !rc; return rc; } @@ -152,21 +150,21 @@ bool ReSimpleMatcher::match(const ReByteBuffer& toTest, ReHit* hit) const{ * false: otherwise */ bool ReSimpleMatcher::searchTokens(const ReByteBuffer& toTest, int from, int to, - ReHit* hit, bool greedy) const{ + ReHit* hit, bool greedy) const { bool rc = true; - if (! greedy){ + if (!greedy) { int current = 0; - for (int ix = from; ix <= to; ix++){ + for (int ix = from; ix <= to; ix++) { size_t length = m_tokens.strLengthOf(ix); if (length == 0) continue; current = toTest.indexOf(m_tokens.strOf(ix), length, current, -1, - m_ignoreCase); - if (current < 0){ + m_ignoreCase); + if (current < 0) { rc = false; break; } - if (hit != NULL){ + if (hit != NULL) { hit->setStart(current); hit->setEnd(current + length); } @@ -189,17 +187,18 @@ bool ReSimpleMatcher::searchTokens(const ReByteBuffer& toTest, int from, int to, * m_notPattern: the name matches not
* false: otherwise */ -bool ReSimpleMatcher::search(const ReByteBuffer& toTest, ReHit* hit, bool greedy) const{ +bool ReSimpleMatcher::search(const ReByteBuffer& toTest, ReHit* hit, + bool greedy) const { bool rc = m_findAll; - if (! rc){ + if (!rc) { size_t last = m_tokens.count(); size_t length0 = m_tokens.strLengthOf(0); size_t lengthLast = m_tokens.strLengthOf(last); rc = searchTokens(toTest, length0 == 0 ? 1 : 0, - lengthLast == 0 ? last - 1 : last, hit, greedy); + lengthLast == 0 ? last - 1 : last, hit, greedy); } if (m_notPattern) - rc = ! rc; + rc = !rc; return rc; } /** @@ -209,7 +208,8 @@ bool ReSimpleMatcher::search(const ReByteBuffer& toTest, ReHit* hit, bool greedy * @param prefix NULL or a prefix of the output * @return buffer.str() (for chaining) */ -const char* ReSimpleMatcher::status(ReByteBuffer& buffer, const char* prefix) const{ +const char* ReSimpleMatcher::status(ReByteBuffer& buffer, + const char* prefix) const { if (prefix != NULL) buffer.append(prefix); m_pattern.status(buffer, "pattern: "); @@ -221,20 +221,19 @@ const char* ReSimpleMatcher::status(ReByteBuffer& buffer, const char* prefix) co * Constructor. */ RePatternList::RePatternList() : - m_patternString(), - m_patterns(NULL), - m_count(0) -{ + m_patternString(), + m_patterns(NULL), + m_count(0) { } /** * Destructor. */ -RePatternList::~RePatternList(){ +RePatternList::~RePatternList() { destroy(); } -void RePatternList::destroy(){ - if (m_patterns != NULL){ - for (int ix = 0; ix < m_count; ix++){ +void RePatternList::destroy() { + if (m_patterns != NULL) { + for (int ix = 0; ix < m_count; ix++) { delete m_patterns[ix]; m_patterns[ix] = NULL; } @@ -249,11 +248,11 @@ void RePatternList::destroy(){ * @param fp target file pointer * @param prefix NULL or a introduction */ -void RePatternList::dump(FILE* fp, const char* prefix) const{ +void RePatternList::dump(FILE* fp, const char* prefix) const { ReByteBuffer buffer; if (prefix != NULL) fprintf(fp, "%s\n", prefix); - for (int ix = 0; ix < m_count; ix++){ + for (int ix = 0; ix < m_count; ix++) { fprintf(fp, "%d: ", ix); m_patterns[ix]->dump(fp, NULL); } @@ -274,18 +273,18 @@ void RePatternList::dump(FILE* fp, const char* prefix) const{ * false: no pattern matches or at least one * "not-pattern" matches */ -bool RePatternList::match(const ReByteBuffer& name){ +bool RePatternList::match(const ReByteBuffer& name) { bool rc = false; int count = m_startNot < 0 ? m_count : m_count - m_startNot + 1; // matches at least one positive pattern? for (int ix = 0; ix < count; ix++) - if (m_patterns[ix]->match(name)){ + if (m_patterns[ix]->match(name)) { rc = true; break; } - if (rc && m_startNot >= 0){ + if (rc && m_startNot >= 0) { for (int ix = m_startNot; ix < m_count; ix++) - if (m_patterns[ix]->match(name)){ + if (m_patterns[ix]->match(name)) { rc = false; break; } @@ -305,11 +304,11 @@ bool RePatternList::match(const ReByteBuffer& name){ * NULL: no not prefix exists */ void RePatternList::set(const char* patterns, bool ignoreCase, - const char* separator, const char* notPrefix){ + const char* separator, const char* notPrefix) { char buffer[2]; destroy(); - m_patternString = patterns; - if (separator == NULL){ + m_patternString = patterns; + if (separator == NULL) { buffer[0] = patterns[0]; buffer[1] = '\0'; separator = buffer; @@ -318,7 +317,7 @@ void RePatternList::set(const char* patterns, bool ignoreCase, int sepLength = strlen(separator); ReByteBuffer theNotPattern(notPrefix == NULL ? "" : notPrefix); ReByteBuffer thePatterns(patterns); - if (thePatterns.endsWith(separator)){ + if (thePatterns.endsWith(separator)) { thePatterns.setLength(thePatterns.length() - sepLength); } m_count = thePatterns.count(separator) + 1; @@ -327,13 +326,13 @@ void RePatternList::set(const char* patterns, bool ignoreCase, int ixInsert = 0; int current = 0; int last = 0; - while( (current = thePatterns.indexOf(separator, sepLength, last)) != -1){ - ixInsert = setOne(ixInsert, thePatterns.str() + last, current - last, ignoreCase, - theNotPattern); + while ((current = thePatterns.indexOf(separator, sepLength, last)) != -1) { + ixInsert = setOne(ixInsert, thePatterns.str() + last, current - last, + ignoreCase, theNotPattern); last = current + sepLength; } setOne(ixInsert, patterns + last, strlen(thePatterns.str() + last), - ignoreCase, theNotPattern); + ignoreCase, theNotPattern); if (m_startNot >= m_count) m_startNot = -1; } @@ -353,16 +352,16 @@ void RePatternList::set(const char* patterns, bool ignoreCase, * ix + 1: otherwise */ int RePatternList::setOne(int index, const char* pattern, size_t patternLength, - bool ignoreCase, const ReByteBuffer& notPrefix){ - ReByteBuffer thePattern (pattern, patternLength); + bool ignoreCase, const ReByteBuffer& notPrefix) { + ReByteBuffer thePattern(pattern, patternLength); bool isNotPattern = (notPrefix.length() > 0 - && thePattern.startsWith(notPrefix.str(), notPrefix.length())); + && thePattern.startsWith(notPrefix.str(), notPrefix.length())); int start = isNotPattern ? notPrefix.length() : 0; // not patterns will be inserted at the bottom: int ix = isNotPattern ? --m_startNot : index; m_patterns[ix] = new ReSimpleMatcher(thePattern.str() + start); m_patterns[ix]->setIgnoreCase(ignoreCase); - return isNotPattern ? index: index + 1; + return isNotPattern ? index : index + 1; } /** @@ -372,10 +371,11 @@ int RePatternList::setOne(int index, const char* pattern, size_t patternLength, * @param prefix NULL or a prefix of the output * @return buffer.str() (for chaining) */ -const char* RePatternList::status(ReByteBuffer& buffer, const char* prefix) const{ +const char* RePatternList::status(ReByteBuffer& buffer, + const char* prefix) const { if (prefix != NULL) buffer.append(prefix); - for (int ix = 0; ix < m_count; ix++){ + for (int ix = 0; ix < m_count; ix++) { buffer.appendInt(ix).append(": ", 2); m_patterns[ix]->status(buffer, NULL); } diff --git a/string/ReMatcher.hpp b/string/ReMatcher.hpp index 5e34f1c..1381396 100644 --- a/string/ReMatcher.hpp +++ b/string/ReMatcher.hpp @@ -42,7 +42,7 @@ public: virtual bool compile(const char* pattern) = 0; virtual bool match(const ReByteBuffer& toTest, ReHit* hit = NULL) const = 0; virtual bool search(const ReByteBuffer& toTest, ReHit* hit = NULL, - bool greedy = false) const = 0; + bool greedy = false) const = 0; public: inline bool isIgnoreCase() const { return m_ignoreCase; @@ -76,17 +76,17 @@ public: void dump(FILE* fp, const char* prefix) const; virtual bool match(const ReByteBuffer& toTest, ReHit* hit = NULL) const; virtual bool search(const ReByteBuffer& toTest, ReHit* hit = NULL, - bool greedy = false) const; + bool greedy = false) const; /** Sets the mode whether the case will be ignored or not. * @param onNotOff true: the case will be ignored. */ - void setIgnoreCase(bool onNotOff){ + void setIgnoreCase(bool onNotOff) { m_ignoreCase = onNotOff; } const char* status(ReByteBuffer& buffer, const char* prefix) const; protected: - bool searchTokens(const ReByteBuffer& toTest, int from, int to, - ReHit* hit, bool greedy) const; + bool searchTokens(const ReByteBuffer& toTest, int from, int to, ReHit* hit, + bool greedy) const; private: ReByteBuffer m_pattern; ReStringList m_tokens; @@ -101,9 +101,9 @@ public: /** @brief Returns the number of entries in the list. * @return the count of patterns in the list */ - inline int count() const { - return m_count; - } + inline int count() const { + return m_count; + } void destroy(); void dump(FILE* fp, const char* prefix) const; bool match(const ReByteBuffer& name); @@ -111,29 +111,30 @@ public: * @param name the string to Test * @return true: the string matches */ - inline bool match(const char* name){ + inline bool match(const char* name) { return match(ReByteBuffer(name)); } - /** Returns the original pattern string. - * @return the string describing the patterns. - */ - const char* patternString() const - { return m_patternString.str(); } + /** Returns the original pattern string. + * @return the string describing the patterns. + */ + const char* patternString() const { + return m_patternString.str(); + } void set(const char* patterns, bool ignoreCase = false, - const char* separator = NULL, const char* notPrefix = "-"); + const char* separator = NULL, const char* notPrefix = "-"); const char* status(ReByteBuffer& buffer, const char* prefix) const; /** Sets the mode whether the case will be ignored or not. * @param onNotOff true: the case will be ignored. */ - void setIgnoreCase(bool onNotOff){ + void setIgnoreCase(bool onNotOff) { for (int ii = 0; ii < m_count; ii++) m_patterns[ii]->setIgnoreCase(onNotOff); } private: int setOne(int index, const char* pattern, size_t patternLength, - bool ignoreCase, const ReByteBuffer& notPrefix); + bool ignoreCase, const ReByteBuffer& notPrefix); private: - ReByteBuffer m_patternString; + ReByteBuffer m_patternString; // store of all patterns: the not patterns are at the bottom ReSimpleMatcher** m_patterns; // count of all patterns (including not patterns: