* 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.
* @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);
* @param sourceLength length of <code>source</code>
*/
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);
}
/** @brief Destructor.
*
*/
-ReByteBuffer::~ReByteBuffer(){
+ReByteBuffer::~ReByteBuffer() {
if (m_buffer != m_primaryBuffer)
delete[] m_buffer;
m_buffer = NULL;
* @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());
}
*
* @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;
*
* @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;
*
* @return *this (for chaining)
*/
-ReByteBuffer& ReByteBuffer::append(const ReByteBuffer& source){
+ReByteBuffer& ReByteBuffer::append(const ReByteBuffer& source) {
return append(source.str(), source.length());
}
*
* @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);
* @param padding character used for padding (see <code>minLength</code>)
* @return <code>*this</code> (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;
* @return <code>*this</code> (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.
*
* @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);
*
* @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);
*
* @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);
*
* @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);
* > 12: at least dd:HH:MM:SS.sss<br>
* @return <code>buffer</code> (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;
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'.
* > 10: at least dd:HH:MM:SS<br>
* @return <code>buffer</code> (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;
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.
* @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';
}
}
* @param lengthOfToCount -1: length is <code>strlen(toCount)</count><br>
* otherwise: length of <code>toCount</count>
*/
-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;
}
* <code>false</code>: 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;
}
*
* @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':
* @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);
* @return -1: both byte sequences are equal<br>
* 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)
* Otherwise: the index of <code>toFind</code> 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++;
* Otherwise: the index of <code>toFind</code> 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;
}
* @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;
}
* 0: delta is set to a default value<br>
* < 0: the current capacity will be doubled until <code>- delta</code>
*/
-void ReByteBuffer::setDelta(int delta){
+void ReByteBuffer::setDelta(int delta) {
m_delta = delta == 0 ? PRIMARY_BUFFER_SIZE : 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';
* 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);
* @return true: Success. false: <code>ix</code> 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)
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 {
* @return <code>true</code>: the buffer starts with <code>head</code><br>
* <code>false</code>: 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;
* @param prefix NULL or a prefix of the output
* @return <code>buffer.str()</code> (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();
}
#define REBYTEBUFFER_H_
#define PRIMARY_BUFFER_SIZE 513
-#define INLINE
/** @brief An efficient dynamic memory buffer.
*
* Implements a very efficient dynamic byte sequence.
* @param aChar character to append
* @return <code>*this</code> (for chaining)
*/
- INLINE ReByteBuffer& appendChar(char aChar){
+ inline ReByteBuffer& appendChar(char aChar) {
setLength(m_length + 1);
m_buffer[m_length - 1] = aChar;
return *this;
* @param count number of times to append
* @return <code>*this</code> (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");
* @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 <code>*this</code> (for chaining)
*/
- INLINE ReByteBuffer& ensureLastChar(char aChar){
+ inline ReByteBuffer& ensureLastChar(char aChar) {
if (lastChar() != aChar)
appendChar(aChar);
return *this;
* @param ignoreCase <code>true</code>: case insensitive comparison
* @return <code>true</code>: 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.
* @param ignoreCase <code>true</code>: case insensitive comparison
* @return <code>true</code>: 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.
*
* @return true: Success. false: <code>ix</code> 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<br>
* 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);
*
* @return true: Success. false: <code>ix</code> 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 <code>*this</code> (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;
* @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 <code>source</code>.
* @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 <code>getBuffer()</code>.
* @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 <code>m_primaryBuffer</code> if the space is small enough.
- char* m_buffer;
- //@ The used bytes in <code>m_buffer</code>.
- size_t m_length;
- //@ The size of <code>m_buffer</code>.
- 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 <code>m_primaryBuffer</code> if the space is small enough.
+ char* m_buffer;
+ //@ The used bytes in <code>m_buffer</code>.
+ size_t m_length;
+ //@ The size of <code>m_buffer</code>.
+ size_t m_capacity;
//@ number of reallocation in ensureSize()
int m_reallocation;
};
* @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);
*/
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
#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
*
* @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);
}
*
* @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();
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);
}
*
* @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;
* @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
*
* @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;
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;
}
#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;
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.
return m_valid;
}
protected:
- ReByteBuffer m_filename;
- bool m_valid;
+ ReByteBuffer m_filename;
+ bool m_valid;
};
#endif /* RECONFIGFILE_H_ */
/** @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
}
/** @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;
}
* @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;
}
/**
* @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.
*
*
* @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);
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;
* @return true: a file has been found<br>
* 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;
*
* @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;
#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;
}
*
* @return <code>path</code> (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
}
*
* @return true: The instance is OK. false: Some error has occurred.
*/
-bool ReDirectory::isValid(){
+bool ReDirectory::isValid() {
return m_valid;
}
*
* @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;
}
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);
*
* @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
#define REFILEFINDER_H_
/** <code>ReDirectory</code> searches files using pattern matching and/or file date.
*/
-class ReDirectory{
+class ReDirectory {
public:
ReDirectory();
ReDirectory(const char* path);
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_ */
* This constructor is for derived classes only.
* The constructor of the derived class must fill the <code>m_message</code>.
*/
-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.
*
* @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());
* @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);
}
* @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);
}
* @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);
}
* @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);
}
/** @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);
/** @brief Returns the message.
* @returns The description of the exception.
*/
- inline const char* getMessage() const{
+ inline const char* getMessage() const {
return m_message;
}
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_ */
#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 <code>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 <code>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);
/** @brief Deletes all entries in the list.
*/
-void ReHashList::clear(){
+void ReHashList::clear() {
m_keys.clear();
m_values.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());
}
}
*
* @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;
}
* @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;
*
* @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;
}
* @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;
* @param value The value byte sequence.
* @param valueLength The length of <code>value</code>.
*/
-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 {
* @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.
* @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());
}
* @param valueSpace reserve the space for this amount of value string space.<br>
* < 0: the current space will be doubled until <code>-valueSpace</code>
*/
-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);
}
* 1: maximal string length = 255,<br>
* 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);
}
* @param prefix NULL or a prefix of the output
* @return <code>buffer.str()</code> (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: ");
return buffer.str();
}
-
-
#ifndef REHASHLIST_H_
#define REHASHLIST_H_
-class ReArrayPosition{
+class ReArrayPosition {
public:
ReArrayPosition();
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);
#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 <code>i18nf(const char* key)</code>
//@ Because of this <code>i18nf(const char* key)</code> is not reentrant.
-ReVarArgs ReI18N::m_varArgs;
-
+ReVarArgs ReI18N::m_varArgs;
/** @brief Initializes the module.
*
*/
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");
* @param count The number of entries in <code>translation</code>.
* @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;
*
* @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;
}
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);
* @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;
}
*
* @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.
*
* @return The variant argument instance <code>args</code> 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
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.
*
* @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");
}
/**
* 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.
*
* @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;
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;
}
}
* @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);
*
* @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;
}
* @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.
* @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);
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);
#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 {
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);
}
}
}
/** @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;
}
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)
}
/** @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;
}
}
/** @brief Destructor.
*/
-ReLogger::~ReLogger(){
+ReLogger::~ReLogger() {
delete m_stdConsoleAppender;
m_stdConsoleAppender = NULL;
delete m_stdFileAppender;
*
* @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);
*
* @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;
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.
*
* @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;
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;
}
* 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);
* 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
};
/**
* 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.
*/
/**
* Implements an abstract base class for handling of the output of an logger.
*/
-class ReAppender{
+class ReAppender {
public:
ReAppender();
virtual ~ReAppender();
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();
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.
* 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();
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);
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() {
* @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());
}
* @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);
* It may contain <code>'\\n'</code> for separate lines.
* @param examples A string with one ore more calling examples.
* It may contain <code>'\\n'</code> 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);
*
* @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.
*
* @param defaultValue The default value of the option.
* @param lengthValue The length of <code>defaultValue</code>.
*/
-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:
* * @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.
* @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.
* @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.
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';
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);
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;
}
*
* @return The count of arguments.
*/
-int ReProgramArgs::getArgCount() const{
+int ReProgramArgs::getArgCount() const {
return m_argCount;
}
*
* @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)
*
* @return The name of the application.
*/
-const char* ReProgramArgs::getProgramName() const{
+const char* ReProgramArgs::getProgramName() const {
return m_program;
}
* @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
* @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:
* @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;
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;
*
* @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);
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:
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;
}
*
* @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++;
}
*
* @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("<options>:"));
}
ReByteBuffer name;
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("<number>"), -1);
break;
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);
}
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);
};
/**
* <p>The connection between definition and retrieval are names.</p>
*/
class ReProgramArgs {
- static const char* PREFIX_LINE_OPTION;
+ static const char* PREFIX_LINE_OPTION;
public:
enum DataType {
DT_UNDEF = 0,
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);
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_ */
#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
* 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.
*/
*
* @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.
*
*
* @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;
* @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;
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);
}
}
* @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<const Sequence*>(
- 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<const Sequence*>(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++;
* < 0: element1 < element2<br>
* > 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;
* @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());
}
}
* @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<const Byte*>(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;
* @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;
}
*
* @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<const uint8_t*>(seq) + m_offsetOfLength;
- switch (m_sizeOfLength){
+ const uint8_t* ptr = reinterpret_cast<const uint8_t*>(seq)
+ + m_offsetOfLength;
+ switch (m_sizeOfLength) {
case 1:
rc = *ptr;
break;
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);
* @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<const uint8_t*>(seq) + m_offsetOfLength;
- switch (m_sizeOfLength){
+ const uint8_t* ptr = reinterpret_cast<const uint8_t*>(seq)
+ + m_offsetOfLength;
+ switch (m_sizeOfLength) {
case 1:
rc = *ptr;
break;
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);
}
}
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(seq) + m_offsetOfTag;
- switch (m_sizeOfTag){
+ switch (m_sizeOfTag) {
case 0:
tag = 0;
break;
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);
*
* @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 {
* @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 {
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);
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());
+ */
}
}
* < 0: the current number of entries will be doubled
* until <code>- maxStringSpace</code> 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
* @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<uint8_t*>(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;
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;
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;
break;
}
}
- if (m_sizeOfTag > 0){
+ if (m_sizeOfTag > 0) {
uint8_t* ptr = reinterpret_cast<uint8_t*>(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;
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;
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;
*
* @param onNotOff <code>true</code>: 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();
*
* @param onNotOff <code>true</code>: 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();
* indiviually stored. <br>
* If > 0 <code>sizeOfLength</code>must 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:
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:
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;
/** @brief Sorts the list.
* Note: the comparison is controlled by <code>m_ignoreCase</code>.
*/
-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++;
* @param prefix NULL or a prefix of the output
* @return <code>buffer.str()</code> (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");
* @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;
memcpy(ptrRoot, ptrChild, m_entrySize);
memcpy(ptrChild, &seq, m_entrySize);
root = child;
- }
- }
+ }
+ }
}
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.
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();
* @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);
}
* 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;
}
* @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;
}
* @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;
*
* @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;
}
* @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)
* @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.
* @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.
* @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);
* @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);
* @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;
}
* @return -1: the index is too large.<br>
* 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;
* Otherwise: the length of the <code>index</code>-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);
}
* Otherwise: the length of the <code>index</code>-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))
*
* @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();
}
*
* @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);
}
*
* @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)
* @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)
* @param append false: the list will be cleared at the beginning.<br>
* 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
* @return <code>buffer</code> (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);
*
* @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);
*
* @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);
* listOut.writeToFile("abc.csv");
* </code></pre>
*/
-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);
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);
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_ */
* 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
list = end + 1;
end = strchr(list, separator);
}
- if (! rc){
+ if (!rc) {
if (ignoreCase)
rc = strnicmp(list, phrase, end - list) == 0;
else
* @result <code>fullpath</code>. (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);
* @result <code>fullpath</code>. (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));
return fullpath;
}
-
/**
* Returns the length of an integer in a given text.
*
* @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;
* @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);
const char* end = strrchr(start, currentSlash);
- if (path != 0){
+ if (path != 0) {
path->setLength(0);
if (end != NULL)
path->append(start, end - start + 1);
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));
*
* @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))
//@ If used in <code>isInList()</code> 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_ */
* @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);
* 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);
}
}
* 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);
}
}
* if not <code>null</code> 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 <code>null</code> value will be logged.
* if <code>null</code> 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);
}
}
* @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.
* @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.
* @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.
* @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 ? "<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 ? "<null>" : current);
}
}
/** @brief Compares a string and a ReByteBuffer. If not equal this will be logged.
* @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.
* @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.
* @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 ? "<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 ? "<null>" : 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.
* @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));
}
}
* @param buffer OUT: the filename will be constructed in this buffer
* @return <code>buffer.str()</code>: 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();
* @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
/** @brief Creates an empty temporary directory.
* the name can be retrieved by <code>getTestDir()</code>.
*/
-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/";
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);
*
* @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);
* </pre>
* @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"
*
* @return the name of a temporary directory
*/
-const char* ReTestUnit::testDir(){
+const char* ReTestUnit::testDir() {
createTestDir();
return m_tempDir.str();
}
* @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);
}
* @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);
}
}
*
* @return <code>! isError</code>
*/
-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.
*
*
* @return <code>! isError</code>
*/
-bool ReTestUnit::logF(bool isError, const char* format, ...){
+bool ReTestUnit::logF(bool isError, const char* format, ...) {
char buffer[2048];
va_list args;
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);
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.
* @param format The format with the placeholders.
* @throws <code>ReFormatException()</code> 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.
* @result A reference for the instance itself. This allows chaining.
* @throws <code>ReFormatException()</code> 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);
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';
}
}
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);
*
* @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);
}
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.
*
* @param value The argument string.
* @param length The length of <code>value</code>.
*/
-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 <code>m_argBuffer</code>.
+ // Store the first index of the argument in <code>m_argBuffer</code>.
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)
*
* @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);
*
* @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);
*
* @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);
*
* @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);
*
* @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;
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;
}
*
* @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);
* 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;
}
* After storing an argument (calling <code>arg()</code>
* <code>trigger->newArg()</code> will be called.
*/
-void ReVarArgs::registerTrigger(ReVarArgTrigger* trigger){
+void ReVarArgs::registerTrigger(ReVarArgTrigger* trigger) {
m_trigger = trigger;
}
/** @brief Marks the end of a <code>arg()</code> chain.
* // The logging is done in the method end().
* </code></pre>
*/
-void ReVarArgs::end(void){
+void ReVarArgs::end(void) {
// Nothing to do in this base class
}
/** This class will be used as callback method for <code>ReVarArgs</code>.
*/
-class ReVarArgTrigger{
+class ReVarArgTrigger {
public:
/** @brief This method will be called when a new <code>ReVarArg::log()</code> call was done.
* The call was done after the insertion of the argument into the internal structures.
* <p>Another known system with this functionality is <code>printf</code>.
* But the <code>ReVarArgs</code> is typesafe.</p>
*/
-class ReVarArgs{
+class ReVarArgs {
private:
static int const STD_SPACE;
static char const PLACE_HOLDER_MARK;
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 <code>asCharPtr()</code>
- //@ 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: <code>m_trigger.newArg()</code> will be called in <code>store()</code>.
+ //@ 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 <code>asCharPtr()</code>
+ //@ 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: <code>m_trigger.newArg()</code> will be called in <code>store()</code>.
ReVarArgTrigger* m_trigger;
};
/** 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_ */
# include <unistd.h>
# include <inttypes.h>
# include <fcntl.h>
- 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)
# define _rmdir(path) rmdir(path)
# define OS_SEPARATOR_CHAR '/'
# define OS_SEPARATOR "/"
-inline int getLastOSError(){
+inline int getLastOSError() {
return errno;
}
#elif defined __WIN32__
# 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
#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);
testReLogger();
extern void testReDirectory(void);
testReDirectory();
- } catch (ReException e){
+ } catch (ReException e) {
fprintf(stderr, "unexpected exception: %s\n", e.getMessage());
}
}
* 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();
testSplice();
testReplace();
}
- void testAppendFix(){
+ void testAppendFix() {
ReByteBuffer buffer;
// maxLength exceeded
// odd maxlength:
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";
checkEqu("y1234a", buffer);
}
- void testEnsureLastChar(){
+ void testEnsureLastChar() {
ReByteBuffer buffer("1/");
buffer.ensureLastChar('/');
checkEqu(2U, buffer.length());
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());
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());
checkEqu("12xyyy", buffer);
}
- void testAppendFloat(){
+ void testAppendFloat() {
ReByteBuffer buffer;
buffer.append(125 / 100.0);
buffer.append(0.333, "%.2f");
checkEqu("1.2500000.33", buffer);
}
- void testAppendInt64(){
+ void testAppendInt64() {
ReByteBuffer buffer;
buffer.appendInt((int64_t) 12345678901ll);
checkEqu("12345678901", buffer);
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:
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
checkF(buffer.startsWith(buffer3.str(), 3, true));
}
- void testEndsWidth(){
+ void testEndsWidth() {
// . . . . . . . . . 01234567
ReByteBuffer buffer("aabbaabb");
// case sensitive
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
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
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());
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);
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);
buffer.set("187654302ab", -1);
checkEqu(187654302, buffer.atoi());
-
buffer.set("y0x1234", -1);
checkEqu(0x1, buffer.atoi(1, 4));
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());
checkEqu(2000u, buf1.capacity());
}
- void testIndexOfCharRIndexOfChar(){
+ void testIndexOfCharRIndexOfChar() {
ReByteBuffer buffer;
buffer.set("123123", -1);
checkEqu(0, buffer.indexOf('1'));
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);
checkF(buf1.insert(8, "/", 1));
}
- void testRemove(){
+ void testRemove() {
ReByteBuffer buf1;
buf1.set("1234567890", 10);
checkT(buf1.remove(0, 2));
checkEqu("", buf1);
checkEqu(0u, buf1.length());
}
- void testReplace(){
+ void testReplace() {
ReByteBuffer buffer;
buffer.set("1234", 4);
buffer.replaceAll("$", 1, "XX", 2);
checkEqu("XXXXxXXXX", buffer);
}
- void testSplice(){
+ void testSplice() {
ReByteBuffer buffer;
buffer.append((Byte*) "12.ab", 5);
};
extern void testReByteBuffer(void);
-void testReByteBuffer(void){
+void testReByteBuffer(void) {
TestReByteBuffer unit;
}
#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");
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;
}
// count of seconds from 1.1.1970 until 1.1.1980:\r
const int tenYear = (365 * 10 + 2) * 24 * 3600;\r
\r
-class TestReDirTools : public ReTestUnit {\r
+class TestReDirTools: public ReTestUnit {\r
public:\r
- TestReDirTools() : ReTestUnit("ReDirTools", __FILE__),\r
- // m_base\r
- // m_buffer\r
- m_testAll(true),\r
- m_logger(ReLogger::globalLogger())\r
- {\r
- m_base = testDir();\r
+ TestReDirTools() :\r
+ ReTestUnit("ReDirTools", __FILE__),\r
+ // m_base\r
+ // m_buffer\r
+ m_testAll(true),\r
+ m_logger(ReLogger::globalLogger()) {\r
+ m_base = testDir();\r
ReDirectory::deleteTree(m_base.str());\r
- m_base.append("dirtool");\r
- _mkdir(m_base.str(), ALLPERMS);\r
+ m_base.append("dirtool");\r
+ _mkdir(m_base.str(), ALLPERMS);\r
m_base.append(OS_SEPARATOR, -1);\r
m_testAll = true;\r
run();\r
ReDirectory::deleteTree(m_base.str(), true);\r
}\r
private:\r
- ReByteBuffer m_base;\r
+ ReByteBuffer m_base;\r
ReByteBuffer m_buffer;\r
bool m_testAll;\r
ReLogger* m_logger;\r
private:\r
- const char* makeDir(const char* relPath){\r
- m_buffer = m_base;\r
- m_buffer.append(relPath);\r
- m_buffer.replaceAll("/", 1, OS_SEPARATOR, -1);\r
- _mkdir(m_buffer.str(), ALLPERMS);\r
- struct stat info;\r
- if (stat(m_buffer.str(), &info) != 0){\r
- logF(true, "cannot create dir %s", m_buffer.str());\r
- }\r
- return m_buffer.str();\r
- }\r
- void makeFile(const char* relPath){\r
- ReByteBuffer path(m_base);\r
- path.append(relPath);\r
- path.replaceAll("/", 1, OS_SEPARATOR, -1);\r
- createFile(path.str(), relPath);\r
- struct stat info;\r
- if (stat(path.str(), &info) != 0){\r
- logF(true, "cannot create file %s", path.str());\r
- }\r
- }\r
- void initTree(){\r
- makeFile("1.txt");\r
- makeDir("dir1");\r
- makeDir("dir2");\r
+ const char* makeDir(const char* relPath) {\r
+ m_buffer = m_base;\r
+ m_buffer.append(relPath);\r
+ m_buffer.replaceAll("/", 1, OS_SEPARATOR, -1);\r
+ _mkdir(m_buffer.str(), ALLPERMS);\r
+ struct stat info;\r
+ if (stat(m_buffer.str(), &info) != 0) {\r
+ logF(true, "cannot create dir %s", m_buffer.str());\r
+ }\r
+ return m_buffer.str();\r
+ }\r
+ void makeFile(const char* relPath) {\r
+ ReByteBuffer path(m_base);\r
+ path.append(relPath);\r
+ path.replaceAll("/", 1, OS_SEPARATOR, -1);\r
+ createFile(path.str(), relPath);\r
+ struct stat info;\r
+ if (stat(path.str(), &info) != 0) {\r
+ logF(true, "cannot create file %s", path.str());\r
+ }\r
+ }\r
+ void initTree() {\r
+ makeFile("1.txt");\r
+ makeDir("dir1");\r
+ makeDir("dir2");\r
makeDir("dir1/cache");\r
- makeDir("dir1/dir1_1");\r
- makeDir("dir1/dir1_2");\r
- makeDir("dir1/dir1_2/dir1_2_1");\r
- makeFile("dir1/dir1_2/dir1_2_1/x1.txt");\r
- makeFile("dir1/dir1_2/dir1_2_1/x2.txt");\r
- makeFile("dir2/2.x");\r
- makeFile("dir1/cache/cache.txt");\r
- }\r
- void run(){\r
+ makeDir("dir1/dir1_1");\r
+ makeDir("dir1/dir1_2");\r
+ makeDir("dir1/dir1_2/dir1_2_1");\r
+ makeFile("dir1/dir1_2/dir1_2_1/x1.txt");\r
+ makeFile("dir1/dir1_2/dir1_2_1/x2.txt");\r
+ makeFile("dir2/2.x");\r
+ makeFile("dir1/cache/cache.txt");\r
+ }\r
+ void run() {\r
initTree();\r
- if (m_testAll){\r
+ if (m_testAll) {\r
testList2();\r
testToolStatistic();\r
testBasic();\r
}\r
}\r
// F:\temp\retestunit\dirtool\r
- void testList2(){\r
+ void testList2() {\r
const char* argv[] = { "dt", "list", "-r", m_base.str(), NULL };\r
ReDirTools tools;\r
tools.main(4, (char**) argv);\r
}\r
- void testList(){\r
- const char* argv[] = { "list", m_base.str(), NULL };\r
- ReDirList(m_logger).run(2, argv);\r
- }\r
- int secOfFileTime(ReFileTime_t data){\r
+ void testList() {\r
+ const char* argv[] = { "list", m_base.str(), NULL };\r
+ ReDirList(m_logger).run(2, argv);\r
+ }\r
+ int secOfFileTime(ReFileTime_t data) {\r
#if defined __linux__\r
return data.tv_sec;\r
#elif defined __WIN32__\r
return (int) ReDirStatus_t::filetimeToTime(&data);\r
#endif\r
}\r
- void testCopyFile(){\r
+ void testCopyFile() {\r
#if defined __linux__\r
- ReByteBuffer src(m_base);\r
- src.append("dir1/dir1_2/dir1_2_1/x1.txt");\r
- ReByteBuffer trg(testDir());\r
- trg.append("copy_x1.txt");\r
- ReByteBuffer buffer;\r
+ ReByteBuffer src(m_base);\r
+ src.append("dir1/dir1_2/dir1_2_1/x1.txt");\r
+ ReByteBuffer trg(testDir());\r
+ trg.append("copy_x1.txt");\r
+ ReByteBuffer buffer;\r
buffer.ensureSize(5);\r
- ReDirSync::copyFile(src.str(), NULL, trg.str(), buffer,\r
+ ReDirSync::copyFile(src.str(), NULL, trg.str(), buffer,\r
ReLogger::globalLogger());\r
- checkFileEqu(src.str(), trg.str());\r
+ checkFileEqu(src.str(), trg.str());\r
#else\r
- log(false, "testCopyFile not implemented");\r
+ log(false, "testCopyFile not implemented");\r
#endif\r
- }\r
+ }\r
\r
- void checkRelDate(ReFileTime_t absTime, int relTime){\r
- int diffNow = int(time(NULL) - secOfFileTime(absTime));\r
- int diff = diffNow * relTime < 0 ? diffNow + relTime : diffNow - relTime;\r
- if (diff < 0)\r
- diff = - diff;\r
- checkT(diff < 2);\r
- }\r
- void testDirOptions(){\r
- class MyOptions : public ReDirOptions{\r
- public:\r
- MyOptions() : ReDirOptions(s_empty, s_empty) {}\r
- public:\r
- int count() { return m_countCompoundUsage; }\r
- const char** usage() { return m_compoundUsage; }\r
- };\r
- static const char* usage1[] = { "line1", "line2", NULL };\r
- static const char* usage2[] = { "x1", "x2", "x3", NULL };\r
- MyOptions opts;\r
- opts.initCompoundUsage(sizeof usage1 + sizeof usage2);\r
- opts.addCompoundUsage(usage1);\r
- opts.addCompoundUsage(usage2);\r
- checkEqu(7, opts.count());\r
- checkEqu("line1", opts.usage()[0]);\r
- checkEqu("line2", opts.usage()[1]);\r
- checkEqu("x1", opts.usage()[2]);\r
- checkEqu("x2", opts.usage()[3]);\r
- checkEqu("x3", opts.usage()[4]);\r
+ void checkRelDate(ReFileTime_t absTime, int relTime) {\r
+ int diffNow = int(time(NULL) - secOfFileTime(absTime));\r
+ int diff =\r
+ diffNow * relTime < 0 ? diffNow + relTime : diffNow - relTime;\r
+ if (diff < 0)\r
+ diff = -diff;\r
+ checkT(diff < 2);\r
+ }\r
+ void testDirOptions() {\r
+ class MyOptions: public ReDirOptions {\r
+ public:\r
+ MyOptions() :\r
+ ReDirOptions(s_empty, s_empty) {\r
+ }\r
+ public:\r
+ int count() {\r
+ return m_countCompoundUsage;\r
+ }\r
+ const char** usage() {\r
+ return m_compoundUsage;\r
+ }\r
+ };\r
+ static const char* usage1[] = { "line1", "line2", NULL };\r
+ static const char* usage2[] = { "x1", "x2", "x3", NULL };\r
+ MyOptions opts;\r
+ opts.initCompoundUsage(sizeof usage1 + sizeof usage2);\r
+ opts.addCompoundUsage(usage1);\r
+ opts.addCompoundUsage(usage2);\r
+ checkEqu(7, opts.count());\r
+ checkEqu("line1", opts.usage()[0]);\r
+ checkEqu("line2", opts.usage()[1]);\r
+ checkEqu("x1", opts.usage()[2]);\r
+ checkEqu("x2", opts.usage()[3]);\r
+ checkEqu("x3", opts.usage()[4]);\r
\r
- // local time: +3600\r
- const int DIFF = 3600;\r
- checkEqu(tenYear + 24*60*60 - DIFF, secOfFileTime(opts.checkDate("1980.01.02")));\r
- checkEqu(tenYear + 24*60*60+3600-DIFF, secOfFileTime(opts.checkDate("1980.01.02/1")));\r
- checkEqu(tenYear + 24*60*60 + 2*3600 + 33*60 - DIFF, secOfFileTime(opts.checkDate("1980.01.02/02:33")));\r
- checkRelDate(opts.checkDate("now-3m"), 3*60);\r
- checkRelDate(opts.checkDate("now-7h"), 7*60*60);\r
- checkRelDate(opts.checkDate("now-5d"), 5*24*60*60);\r
+ // local time: +3600\r
+ const int DIFF = 3600;\r
+ checkEqu(tenYear + 24 * 60 * 60 - DIFF,\r
+ secOfFileTime(opts.checkDate("1980.01.02")));\r
+ checkEqu(tenYear + 24 * 60 * 60 + 3600 - DIFF,\r
+ secOfFileTime(opts.checkDate("1980.01.02/1")));\r
+ checkEqu(tenYear + 24 * 60 * 60 + 2 * 3600 + 33 * 60 - DIFF,\r
+ secOfFileTime(opts.checkDate("1980.01.02/02:33")));\r
+ checkRelDate(opts.checkDate("now-3m"), 3 * 60);\r
+ checkRelDate(opts.checkDate("now-7h"), 7 * 60 * 60);\r
+ checkRelDate(opts.checkDate("now-5d"), 5 * 24 * 60 * 60);\r
\r
- checkEqu(125ll, opts.checkSize("125"));\r
- checkEqu(125ll, opts.checkSize("125b"));\r
- checkEqu(3000ll, opts.checkSize("3k"));\r
- checkEqu(3*1024ll, opts.checkSize("3K"));\r
- checkEqu(4*1000*1000ll, opts.checkSize("4m"));\r
- checkEqu(4*1024*1024ll, opts.checkSize("4M"));\r
- checkEqu(5*1000*1000*1000ll, opts.checkSize("5g"));\r
- checkEqu(5*1024*1024*1024ll, opts.checkSize("5G"));\r
+ checkEqu(125ll, opts.checkSize("125"));\r
+ checkEqu(125ll, opts.checkSize("125b"));\r
+ checkEqu(3000ll, opts.checkSize("3k"));\r
+ checkEqu(3 * 1024ll, opts.checkSize("3K"));\r
+ checkEqu(4 * 1000 * 1000ll, opts.checkSize("4m"));\r
+ checkEqu(4 * 1024 * 1024ll, opts.checkSize("4M"));\r
+ checkEqu(5 * 1000 * 1000 * 1000ll, opts.checkSize("5g"));\r
+ checkEqu(5 * 1024 * 1024 * 1024ll, opts.checkSize("5G"));\r
\r
- }\r
- void checkSetFilterFromProgramArgs(){\r
- ReDirOptions opts(s_empty, s_empty);\r
- opts.addStandardFilterOptions();\r
- const char* argv[] = { "x", "-y1980.01.02", "-o1980.01.03",\r
- "-D5", "-d1", "-z1k", "-Z2M", "-p;*;-*~"\r
- };\r
- ReDirEntryFilter_t filter;\r
- opts.programArgsChangeable().init(sizeof argv / sizeof argv[0], argv);\r
- opts.setFilterFromProgramArgs(filter);\r
- // local time: +3600\r
- const int DIFF = 3600;\r
- checkEqu(tenYear + 1*24*3600 - DIFF, secOfFileTime(filter.m_maxAge));\r
- checkEqu(tenYear + 2*24*3600 - DIFF, secOfFileTime(filter.m_minAge));\r
- checkEqu(5, (int) filter.m_maxDepth);\r
- checkEqu(1, (int) filter.m_minDepth);\r
- checkEqu(1000ll, filter.m_minSize);\r
- checkEqu(2*1024*1024ll, filter.m_maxSize);\r
- checkNN(filter.m_nodePatterns);\r
- checkEqu(";*;-*~", filter.m_nodePatterns->patternString());\r
- }\r
- void checkOneFile(const char* node, const char* parent, const ReHashList& hash){\r
- ReByteBuffer path, expected;\r
- checkT(hash.get(ReByteBuffer(node), path));\r
- expected.set(parent, -1);\r
- if (! expected.endsWith(OS_SEPARATOR))\r
- expected.append(OS_SEPARATOR);\r
- if (! path.endsWith(expected.str(), -1))\r
- checkT(false); \r
- }\r
- void testBasic(){\r
+ }\r
+ void checkSetFilterFromProgramArgs() {\r
+ ReDirOptions opts(s_empty, s_empty);\r
+ opts.addStandardFilterOptions();\r
+ const char* argv[] = { "x", "-y1980.01.02", "-o1980.01.03", "-D5",\r
+ "-d1", "-z1k", "-Z2M", "-p;*;-*~" };\r
+ ReDirEntryFilter_t filter;\r
+ opts.programArgsChangeable().init(sizeof argv / sizeof argv[0], argv);\r
+ opts.setFilterFromProgramArgs(filter);\r
+ // local time: +3600\r
+ const int DIFF = 3600;\r
+ checkEqu(tenYear + 1 * 24 * 3600 - DIFF,\r
+ secOfFileTime(filter.m_maxAge));\r
+ checkEqu(tenYear + 2 * 24 * 3600 - DIFF,\r
+ secOfFileTime(filter.m_minAge));\r
+ checkEqu(5, (int ) filter.m_maxDepth);\r
+ checkEqu(1, (int ) filter.m_minDepth);\r
+ checkEqu(1000ll, filter.m_minSize);\r
+ checkEqu(2 * 1024 * 1024ll, filter.m_maxSize);\r
+ checkNN(filter.m_nodePatterns);\r
+ checkEqu(";*;-*~", filter.m_nodePatterns->patternString());\r
+ }\r
+ void checkOneFile(const char* node, const char* parent,\r
+ const ReHashList& hash) {\r
+ ReByteBuffer path, expected;\r
+ checkT(hash.get(ReByteBuffer(node), path));\r
+ expected.set(parent, -1);\r
+ if (!expected.endsWith(OS_SEPARATOR))\r
+ expected.append(OS_SEPARATOR);\r
+ if (!path.endsWith(expected.str(), -1))\r
+ checkT(false);\r
+ }\r
+ void testBasic() {\r
ReTraverser traverser(m_base.str());\r
RePatternList patterns;\r
// exclude */cache/*\r
int level = 0;\r
ReDirStatus_t* entry;\r
ReHashList hash;\r
- while( (entry = traverser.rawNextFile(level)) != NULL){\r
+ while ((entry = traverser.rawNextFile(level)) != NULL) {\r
hash.put(ReByteBuffer(entry->node(), -1), entry->m_path);\r
- logF(false, "%d: %-12s %2d %s",\r
- level, entry->node(),\r
- int(entry->fileSize()),\r
- entry->m_path.str());\r
+ logF(false, "%d: %-12s %2d %s", level, entry->node(),\r
+ int(entry->fileSize()), entry->m_path.str());\r
}\r
checkOneFile("x1.txt", "dir1_2_1", hash);\r
checkOneFile("x2.txt", "dir1_2_1", hash);\r
checkOneFile("dir1_2", "dir1", hash);\r
checkF(hash.get("cache.txt", buffer));\r
}\r
- void testDirStatistic(){\r
+ void testDirStatistic() {\r
ReDirStatistic stat(m_logger);\r
const ReStringList& list = stat.calculate(m_base.str(), 1);\r
ReByteBuffer buffer;\r
- ReByteBuffer expected;\r
+ ReByteBuffer expected;\r
log(false, list.join("\n", buffer).str());\r
checkEqu(3u, list.count());\r
- // "1 t:\temp\winfried\2\retestunit\dir1\n"\r
- buffer.set(list.strOf(0), list.strLengthOf(0));\r
- checkT(buffer.startsWith("1\t"));\r
- expected.set(m_base.str(), m_base.length()).append("dir1", -1)\r
- .append(OS_SEPARATOR);\r
- // .append(OS_SEPARATOR, -1)\r
- checkT(buffer.endsWith(expected.str()));\r
- \r
- buffer.setLength(0);\r
- const ReStringList& list2 = stat.calculate(m_base.str(), 1, formatWithSizeFilesAndDirs);\r
+ // "1 t:\temp\winfried\2\retestunit\dir1\n"\r
+ buffer.set(list.strOf(0), list.strLengthOf(0));\r
+ checkT(buffer.startsWith("1\t"));\r
+ expected.set(m_base.str(), m_base.length()).append("dir1", -1).append(\r
+ OS_SEPARATOR);\r
+ // .append(OS_SEPARATOR, -1)\r
+ checkT(buffer.endsWith(expected.str()));\r
+\r
+ buffer.setLength(0);\r
+ const ReStringList& list2 = stat.calculate(m_base.str(), 1,\r
+ formatWithSizeFilesAndDirs);\r
log(false, list2.join("\n", buffer).str());\r
- \r
- buffer.set(list.strOf(0), list.strLengthOf(0));\r
- checkT(buffer.startsWith(" 0.000074 MB 3 4\t"));\r
- expected.set(m_base.str(), m_base.length()).append("dir1", -1)\r
- .append(OS_SEPARATOR);\r
- checkT(buffer.endsWith(expected.str()));\r
\r
- buffer.set(list.strOf(1), list.strLengthOf(1));\r
- checkT(buffer.startsWith(" 0.000008 MB 1 0\t"));\r
- expected.set(m_base.str(), m_base.length()).append("dir2", -1)\r
- .append(OS_SEPARATOR);\r
- checkT(buffer.endsWith(expected.str()));\r
+ buffer.set(list.strOf(0), list.strLengthOf(0));\r
+ checkT(buffer.startsWith(" 0.000074 MB 3 4\t"));\r
+ expected.set(m_base.str(), m_base.length()).append("dir1", -1).append(\r
+ OS_SEPARATOR);\r
+ checkT(buffer.endsWith(expected.str()));\r
+\r
+ buffer.set(list.strOf(1), list.strLengthOf(1));\r
+ checkT(buffer.startsWith(" 0.000008 MB 1 0\t"));\r
+ expected.set(m_base.str(), m_base.length()).append("dir2", -1).append(\r
+ OS_SEPARATOR);\r
+ checkT(buffer.endsWith(expected.str()));\r
\r
- buffer.set(list.strOf(2), list.strLengthOf(2));\r
- checkT(buffer.startsWith(" 0.000087 MB 5 6\t"));\r
- expected.set(m_base.str(), m_base.length());\r
- }\r
- /**\r
+ buffer.set(list.strOf(2), list.strLengthOf(2));\r
+ checkT(buffer.startsWith(" 0.000087 MB 5 6\t"));\r
+ expected.set(m_base.str(), m_base.length());\r
+ }\r
+ /**\r
* Tests a file with a given context.\r
*\r
* @param filename name of the file to test\r
* @param content expected content: each line must contain a '*',\r
* separating the start of line and the end of line\r
*/\r
- void checkFile(ReByteBuffer& filename, const char* content){\r
+ void checkFile(ReByteBuffer& filename, const char* content) {\r
ReStringList current;\r
current.readFromFile(filename.str());\r
ReStringList expected;\r
checkEqu(expected.count(), current.count());\r
ReByteBuffer line;\r
ReStringList cols;\r
- for (size_t ix = 0; ix < current.count(); ix++){\r
+ for (size_t ix = 0; ix < current.count(); ix++) {\r
line.setLength(0).append(current.strOf(ix), -1);\r
#if defined __WIN32__\r
line.replaceAll("/", 1, OS_SEPARATOR, 1);\r
#endif\r
cols.split(expected.strOf(ix), '*');\r
const char* col1 = cols.strOf(0);\r
- if (! line.startsWith(col1))\r
+ if (!line.startsWith(col1))\r
checkEqu(col1, line);\r
const char* col2 = cols.strOf(1);\r
- if (! line.endsWith(col2)){\r
+ if (!line.endsWith(col2)) {\r
checkEqu(col2, line);\r
}\r
}\r
- }\r
- void testTouch(){\r
+ }\r
+ void testTouch() {\r
ReByteBuffer nameCurrent;\r
buildFilename("current", nameCurrent);\r
ReByteBuffer optOutput("--output-file=");\r
optOutput.append(nameCurrent);\r
ReDirTools tools;\r
const char* argv[] = { "dt", "touch", "-P;*;-cache", "-tr", "-p;*.txt",\r
- "-m2015.03.28/10:21:31", optOutput.str(), m_base.str(), NULL };\r
+ "-m2015.03.28/10:21:31", optOutput.str(), m_base.str(), NULL };\r
tools.main(8, (char**) argv);\r
\r
checkFile(nameCurrent,\r
- "2015.03.28 10:21:31 *dirtool/1.txt\n"\r
- "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n"\r
- "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n"\r
- "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n"\r
- "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec");\r
+ "2015.03.28 10:21:31 *dirtool/1.txt\n"\r
+ "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n"\r
+ "2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n"\r
+ "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n"\r
+ "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec");\r
\r
- const char* argv2[] = { "dt", "list", "-P;*;-cache", "-tr", "-p;*.txt", "-h",\r
- optOutput.str(), m_base.str(), NULL };\r
+ const char* argv2[] = { "dt", "list", "-P;*;-cache", "-tr", "-p;*.txt",\r
+ "-h", optOutput.str(), m_base.str(), NULL };\r
tools.main(8, (char**) argv2);\r
\r
checkFile(nameCurrent,\r
- " 0.000005 2015.03.28 10:21:31 *dirtool/1.txt\n"\r
- " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n"\r
- " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n"\r
- "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n"\r
- "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec");\r
+ " 0.000005 2015.03.28 10:21:31 *dirtool/1.txt\n"\r
+ " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x1.txt\n"\r
+ " 0.000027 2015.03.28 10:21:31 *dirtool/dir1/dir1_2/dir1_2_1/x2.txt\n"\r
+ "=== filtered: 3 file(s) 0.000059 MByte 0 dirs(s) */sec\n"\r
+ "=== total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec");\r
\r
}\r
- void testBatch(){\r
+ void testBatch() {\r
ReByteBuffer nameCurrent;\r
buildFilename("current", nameCurrent);\r
ReByteBuffer optOutput("--output-file=");\r
optOutput.append(nameCurrent);\r
ReDirTools tools;\r
- const char* argv[] = { "dt", "batch", "-P;*;-cache", "-td", "-cmyscript",\r
- optOutput.str(), m_base.str(), NULL };\r
+ const char* argv[] = { "dt", "batch", "-P;*;-cache", "-td",\r
+ "-cmyscript", optOutput.str(), m_base.str(), NULL };\r
tools.main(7, (char**) argv);\r
#if defined __linux__\r
static const char* content = "#! /bin/sh*\n"\r
- "myscript '*dirtool/dir1'\n"\r
- "myscript '*dirtool/dir2'\n"\r
- "myscript '*dirtool/dir1/dir1_1'\n"\r
- "myscript '*dirtool/dir1/dir1_2'\n"\r
- "myscript '*dirtool/dir1/cache'\n"\r
- "myscript '*dirtool/dir1/dir1_2/dir1_2_1'\n"\r
- "# === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) */sec\n"\r
- "# === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec";\r
+ "myscript '*dirtool/dir1'\n"\r
+ "myscript '*dirtool/dir2'\n"\r
+ "myscript '*dirtool/dir1/dir1_1'\n"\r
+ "myscript '*dirtool/dir1/dir1_2'\n"\r
+ "myscript '*dirtool/dir1/cache'\n"\r
+ "myscript '*dirtool/dir1/dir1_2/dir1_2_1'\n"\r
+ "# === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) */sec\n"\r
+ "# === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec";\r
#elif defined __WIN32__\r
static const char* content = "rem this batch is created by*dirtool\n"\r
- "call myscript *dirtool\\dir1\"\n"\r
- "call myscript *dirtool\\dir2\"\n"\r
- "call myscript *dirtool\\dir1\\cache\"\n"\r
- "call myscript *dirtool\\dir1\\dir1_1\"\n"\r
- "call myscript *dirtool\\dir1\\dir1_2\"\n"\r
- "call myscript *dirtool\\dir1\\dir1_2\\dir1_2_1\"\n"\r
- "rem === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) *sec\n"\r
- "rem === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec";\r
+ "call myscript *dirtool\\dir1\"\n"\r
+ "call myscript *dirtool\\dir2\"\n"\r
+ "call myscript *dirtool\\dir1\\cache\"\n"\r
+ "call myscript *dirtool\\dir1\\dir1_1\"\n"\r
+ "call myscript *dirtool\\dir1\\dir1_2\"\n"\r
+ "call myscript *dirtool\\dir1\\dir1_2\\dir1_2_1\"\n"\r
+ "rem === filtered: 0 file(s) 0.000000 MByte 6 dirs(s) *sec\n"\r
+ "rem === total: 4 file(s) 0.000067 MByte 6 dirs(s) * sec";\r
#endif\r
checkFile(nameCurrent, content);\r
}\r
- void testToolStatistic(){\r
+ void testToolStatistic() {\r
ReDirTools tools;\r
const char* argv[] = { "dt", "stat", "-P;*;-cache", m_base.str(), "2" };\r
tools.main(5, (char**) argv);\r
}\r
- void testToolSync(){\r
+ void testToolSync() {\r
ReDirTools tools;\r
ReByteBuffer source(m_base);\r
source.append("dir1");\r
target.ensureLastChar(OS_SEPARATOR_CHAR);\r
target.append("synctest", -1);\r
_mkdir(target.str(), ALLPERMS);\r
- const char* argv[] = { "dt", "sync", "-P;*;-cache", "-p;*.txt",\r
- source.str(), target.str() };\r
+ const char* argv[] = { "dt", "sync", "-P;*;-cache", "-p;*.txt", source\r
+ .str(), target.str() };\r
tools.main(6, (char**) argv);\r
}\r
};\r
extern void testReDirTools(void);\r
\r
-void testReDirTools(void){\r
+void testReDirTools(void) {\r
TestReDirTools unit;\r
}\r
*/
#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;
};
extern void testReDirectory(void);
-void testReDirectory(void){
+void testReDirectory(void) {
TestReDirectory unit;
}
*/
#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());
}
};
extern void testReException(void);
-void testReException(void){
+void testReException(void) {
TestReException unit;
}
#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;
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 {
}
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;
checkT(hash.get("ab", -1, value));
checkEqu("999", value);
}
- void testNext(){
+ void testNext() {
ReHashList hash;
hash.put("4", "2");
hash.put("1", "8");
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);
};
extern void testReHashList(void);
-void testReHashList(void){
+void testReHashList(void) {
TestReHashList unit;
}
*/
#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;
}
*/
#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;
}
#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;
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();
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);
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;
}
* 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"));
checkT(list.match("a.hpp"));
checkF(list.match("a.hpp~"));
}
- void testMatch(){
+ void testMatch() {
ReSimpleMatcher matcher("abc*.x");
matcher.setIgnoreCase(false);
checkT(matcher.match("abc.X"));
checkT(matcher.match("aBcdef.X"));
}
- void testMatchManyStars(){
+ void testMatchManyStars() {
ReSimpleMatcher matcher("a*b*c*x");
matcher.setIgnoreCase(false);
checkF(matcher.match(""));
checkF(matcher.match("x"));
}
- void testSearch(){
+ void testSearch() {
ReSimpleMatcher matcher("abc*.x");
matcher.setIgnoreCase(false);
checkT(matcher.search("resT"));
checkF(matcher.search("xyz"));
}
- void testSearchManyStars(){
+ void testSearchManyStars() {
ReSimpleMatcher matcher("*a*b*c*x*");
matcher.setIgnoreCase(false);
};
extern void testReMatcher(void);
-void testReMatcher(void){
+void testReMatcher(void) {
TestReMatcher unit;
}
-
-
*/
#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 <opts> <args>\n"
-"This tests the usage of ReProgramArgs\n"
-"\n"
-"<options>:\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[<string>] or --estring=[<string>] Default value: empty\n"
-" This string may be empty\n"
-"-U[<string>] or --estring2=[<string>] Default value: undef2\n"
-" This 2nd string may be empty\n"
-"-i<number> or --intval=<number> Default value: 9\n"
-" This is an integer arg\n"
-"-I<number> or --intval=<number> Default value: 1000\n"
-" This is the 2nd integer arg\n"
-"-s<not empty string> or --string=<not empty string> Default value: 'abc'\n"
-" This string must be non empty\n"
-"-u<not empty string> or --string2=<not empty string> 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 <opts> <args>\nThis tests the usage of ReProgramArgs",
- "$0 -b+ -B- file dir\n\ttest of an example");
+ "test <opts> <args>\n"
+ "This tests the usage of ReProgramArgs\n"
+ "\n"
+ "<options>:\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[<string>] or --estring=[<string>] Default value: empty\n"
+ " This string may be empty\n"
+ "-U[<string>] or --estring2=[<string>] Default value: undef2\n"
+ " This 2nd string may be empty\n"
+ "-i<number> or --intval=<number> Default value: 9\n"
+ " This is an integer arg\n"
+ "-I<number> or --intval=<number> Default value: 1000\n"
+ " This is the 2nd integer arg\n"
+ "-s<not empty string> or --string=<not empty string> Default value: 'abc'\n"
+ " This string must be non empty\n"
+ "-u<not empty string> or --string2=<not empty string> 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 <opts> <args>\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"));
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());
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;
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 <opts> <args>\n"
-"This tests the usage of ReProgramArgs\n"
-"\n"
-"<options>:\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=[<string>] Default value: empty\n"
-" This string may be empty\n"
-"-U[<string>] or --estring2=[<string>] Default value: undef2\n"
-" This 2nd string may be empty\n"
-"-V[<string>] or --estring3=[<string>] Default value: undef3\n"
-" This 3thrd string may be empty\n"
-"-i<number> or --intval=<number> Default value: 9\n"
-" This is an integer arg\n"
-"-s<not empty string> or --string=<not empty 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 <opts> <args>",
- "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 <opts> <args>\n"
+ "This tests the usage of ReProgramArgs\n"
+ "\n"
+ "<options>:\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=[<string>] Default value: empty\n"
+ " This string may be empty\n"
+ "-U[<string>] or --estring2=[<string>] Default value: undef2\n"
+ " This 2nd string may be empty\n"
+ "-V[<string>] or --estring3=[<string>] Default value: undef3\n"
+ " This 3thrd string may be empty\n"
+ "-i<number> or --intval=<number> Default value: 9\n"
+ " This is an integer arg\n"
+ "-s<not empty string> or --string=<not empty 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 <opts> <args>",
+ "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());
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;
};
extern void testReProgramArgs(void);
-void testReProgramArgs(void){
+void testReProgramArgs(void) {
TestReProgramArgs unit;
}
#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);
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);
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;
};
extern void testReRandomizer(void);
-void testReRandomizer(void){
+void testReRandomizer(void) {
TestReRandomizer unit;
}
*/
#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();
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;
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);
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';
}
}
}
- void testSorted(){
+ void testSorted() {
ReSeqArray list;
list.setIgnoreCase(true);
ReByteBuffer value, expectedValue;
checkT(list.binarySearch("cde", -1, index, &tag));
checkEqu(4u, index);
}
- void testIgnoreCase(){
+ void testIgnoreCase() {
ReSeqArray list;
list.setIgnoreCase(true);
ReByteBuffer value, expectedValue;
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);
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));
}
}
- 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());
}
//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;
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());
checkEqu(0u, list.count());
checkF(list.get(0, value));
}
- void testRemove(){
+ void testRemove() {
ReSeqArray list;
ReByteBuffer value;
ReSeqArray::Tag tag = 0;
checkEqu("ghi", value);
checkEqu(300ll, tag);
-
list.remove(1);
checkEqu(2u, list.count());
list.get(0, value, &tag);
};
extern void testReSeqArray(void);
-void testReSeqArray(void){
+void testReSeqArray(void) {
TestReSeqList unit;
}
*/
#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();
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());
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;
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, ';');
list.join(";", value, true);
checkEqu("xxx1;2", value);
}
- void testFile(){
- if (true){
+ void testFile() {
+ if (true) {
ReByteBuffer file;
buildFilename("abc.csv", file);
}
//log(false, "end of testFile()");
}
- void testBase(){
- if (true){
+ void testBase() {
+ if (true) {
ReStringList list;
ReByteBuffer value;
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());
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"));
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"));
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);
};
extern void testReStringList(void);
-void testReStringList(void){
+void testReStringList(void) {
TestReStringList unit;
}
*/
#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);
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));
checkF(ReStringUtils::isInList("aBc", ";abc", false));
}
- void testSplitPath(){
+ void testSplitPath() {
ReByteBuffer fullname, protocol, path, name, ext;
const char* fn = "file:/etc/samba/smb.cnf";
};
extern void testReStringUtils(void);
-void testReStringUtils(void){
+void testReStringUtils(void) {
TestReStringUtils unit;
}
*/
#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);
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;
};
extern void testReTestUnit(void);
-void testReTestUnit(void){
+void testReTestUnit(void) {
TestTestUnit unit;
}
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/*
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);
};
extern void testReTraverser(void);
-void testReTraverser(void){
+void testReTraverser(void) {
TestReTraverser unit;
}
*/
#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);
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());
};
extern void testReVarArgs(void);
-void testReVarArgs(void){
+void testReVarArgs(void) {
TestReVarArgs unit;
}
*/
#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));
};
extern void testReConfigFile(void);
-void testReConfigFile(void){
+void testReConfigFile(void) {
TestReConfigFile unit;
}
static bool s_testAll = true;
-void testBase(){
+void testBase() {
extern void testReSeqArray(void);
testReSeqArray();
testReLogger();
}
-void testString(){
+void testString() {
void testReStringUtils(void);
testReStringUtils();
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());
}
}
\r
#define __LITTLE_ENDIAN__\r
\r
-const int ReMD5::m_s[64] = {\r
- 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\r
- 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\r
- 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\r
- 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21\r
-};\r
+const int ReMD5::m_s[64] = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12,\r
+ 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16,\r
+ 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15,\r
+ 21, 6, 10, 15, 21, 6, 10, 15, 21 };\r
static int s_ix = 0;\r
// for x in [1..64] : int(2**32 * sin(x))\r
-const uint32_t ReMD5::m_K[64] = {\r
- 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\r
- 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\r
- 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\r
- 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\r
- 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\r
- 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\r
- 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\r
- 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\r
- 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\r
- 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\r
- 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\r
- 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\r
- 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\r
- 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\r
- 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\r
- 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391\r
-};\r
+const uint32_t ReMD5::m_K[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db,\r
+ 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8,\r
+ 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e,\r
+ 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,\r
+ 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87,\r
+ 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942,\r
+ 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60,\r
+ 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039,\r
+ 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7,\r
+ 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f,\r
+ 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,\r
+ 0xeb86d391 };\r
\r
/**\r
* Constructor.\r
*/\r
ReMD5::ReMD5() :\r
- //m_digest\r
- // m_hexDigest;\r
- // m_waiting[64];\r
- m_lengthWaiting(0),\r
- m_length(0),\r
- m_a0(0x67452301),\r
- m_b0(0xefcdab89),\r
- m_c0(0x98badcfe),\r
- m_d0(0x10325476),\r
- m_finalized(false)\r
-{\r
+ //m_digest\r
+ // m_hexDigest;\r
+ // m_waiting[64];\r
+ m_lengthWaiting(0),\r
+ m_length(0),\r
+ m_a0(0x67452301),\r
+ m_b0(0xefcdab89),\r
+ m_c0(0x98badcfe),\r
+ m_d0(0x10325476),\r
+ m_finalized(false) {\r
}\r
\r
/**\r
*\r
* @return the binary digest (16 byte array)\r
*/\r
-const uint8_t* ReMD5::digest(){\r
- if (! m_finalized){\r
+const uint8_t* ReMD5::digest() {\r
+ if (!m_finalized) {\r
finalize();\r
}\r
return m_digest;\r
* @param block the rest input (incomplete chunk)\r
* @param blockLength the length of the block: 0..63\r
*/\r
-void ReMD5::finalize(){\r
+void ReMD5::finalize() {\r
uint8_t* block = m_waiting;\r
int blockLength = m_lengthWaiting;\r
// append "1" bit to message\r
*\r
* @return the binary digest (16 byte array)\r
*/\r
-const ReByteBuffer& ReMD5::hexDigest(){\r
- if (m_hexDigest.length() == 0){\r
+const ReByteBuffer& ReMD5::hexDigest() {\r
+ if (m_hexDigest.length() == 0) {\r
digest();\r
- for (int ix = 0; ix < 16; ix++){\r
+ for (int ix = 0; ix < 16; ix++) {\r
m_hexDigest.appendInt(m_digest[ix], "%02x");\r
}\r
}\r
*\r
* This method is a direct programming of the algorithm described in wikipedia.\r
*/\r
-void ReMD5::processChunk2(const uint8_t block[64]){\r
+void ReMD5::processChunk2(const uint8_t block[64]) {\r
uint32_t M[16];\r
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15\r
- for (int ix = 0; ix < 16; ix++){\r
+ for (int ix = 0; ix < 16; ix++) {\r
uint32_t x = block[3];\r
- for (int jj = 2; jj >= 0; jj--){\r
+ for (int jj = 2; jj >= 0; jj--) {\r
x = (x << 8) + block[jj];\r
}\r
M[ix] = x;\r
#if defined TRACE_MD5\r
printf("neu: (%s)\n", block);\r
#endif\r
- for (int i = 0; i < 64; i++){\r
+ for (int i = 0; i < 64; i++) {\r
#if defined TRACE_MD5\r
if (i < 8)\r
printf("%2d: A: %08x B: %08x C: %08x D%08x\n", i, A, B, C, D);\r
#endif\r
- if (i < 16){\r
+ if (i < 16) {\r
# define F1(B, C, D) ((B & C) | (~ B & D))\r
// F := (B and C) or ((not B) and D)\r
F = F1(B, C, D);\r
g = i;\r
- } else if (i < 32){\r
+ } else if (i < 32) {\r
// F := (D and B) or (C and (not D))\r
// g := (5×i + 1) mod 16\r
# define F2(B, C, D) ((D & B) | (C & ~ D))\r
F = F2(B, C, D);\r
- g = (5*i + 1) % 16;\r
- } else if (i < 48){\r
+ g = (5 * i + 1) % 16;\r
+ } else if (i < 48) {\r
// F := B xor C xor D\r
// g := (3×i + 5) mod 16\r
# define F3(B, C, D) ((B ^ C) ^ D)\r
F = F3(B, C, D);\r
- g = (3*i + 5) % 16;\r
+ g = (3 * i + 5) % 16;\r
} else {\r
// F := C xor (B or (not D))\r
# define F4(B, C, D) (C ^ (B | ~ D))\r
// g := (7×i) mod 16\r
F = F4(B, C, D);\r
- g = (7*i) % 16;\r
+ g = (7 * i) % 16;\r
}\r
#if defined TRACE_MD5\r
if (i < 8)\r
printf(" K[%2d]: %08x M[%2d]: %08x shift: %02d\n",\r
- i, m_K[i], g, M[g], m_s[i]);\r
+ i, m_K[i], g, M[g], m_s[i]);\r
#endif\r
uint32_t dTemp = D;\r
D = C;\r
*/\r
#if defined OPTIMIZER_WORKS_GREAT\r
inline void rotate_left_and_add(uint32_t& rc, uint32_t data, int shift, uint32_t term) {\r
- rc = ((data << shift) | (data >> (32-shift))) + term;\r
+ rc = ((data << shift) | (data >> (32-shift))) + term;\r
}\r
-inline void X1(uint32_t &var, uint32_t x, uint32_t y, uint32_t z, \r
- uint32_t data, uint32_t aConst, uint32_t shift) {\r
+inline void X1(uint32_t &var, uint32_t x, uint32_t y, uint32_t z,\r
+ uint32_t data, uint32_t aConst, uint32_t shift) {\r
//#define TRACE_MD5\r
#if defined TRACE_MD5\r
printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z);\r
printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n",\r
- s_ix - 1, aConst, data, shift);\r
+ s_ix - 1, aConst, data, shift);\r
#endif\r
rotate_left_and_add(var, var + F1(x, y, z) + data + aConst, shift, x);\r
}\r
-inline void X2(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, \r
- uint32_t data, uint32_t aConst, uint32_t shift) {\r
+inline void X2(uint32_t& var, uint32_t x, uint32_t y, uint32_t z,\r
+ uint32_t data, uint32_t aConst, uint32_t shift) {\r
#if defined TRACE_MD5\r
printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z);\r
printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n",\r
- s_ix - 1, aConst, data, shift);\r
+ s_ix - 1, aConst, data, shift);\r
#endif\r
- rotate_left_and_add(var, var + F2(x, y, z) + data + aConst, shift, x);\r
+ rotate_left_and_add(var, var + F2(x, y, z) + data + aConst, shift, x);\r
}\r
\r
-inline void X3(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, \r
- uint32_t data, uint32_t aConst, uint32_t shift) {\r
+inline void X3(uint32_t& var, uint32_t x, uint32_t y, uint32_t z,\r
+ uint32_t data, uint32_t aConst, uint32_t shift) {\r
#if defined TRACE_MD5\r
printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z);\r
printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n",\r
- s_ix - 1, aConst, data, shift);\r
+ s_ix - 1, aConst, data, shift);\r
#endif\r
- rotate_left_and_add(var, var + F3(x, y, z) + data + aConst, shift, x);\r
+ rotate_left_and_add(var, var + F3(x, y, z) + data + aConst, shift, x);\r
}\r
\r
-inline void X4(uint32_t& var, uint32_t x, uint32_t y, uint32_t z, \r
- uint32_t data, uint32_t aConst, uint32_t shift) {\r
+inline void X4(uint32_t& var, uint32_t x, uint32_t y, uint32_t z,\r
+ uint32_t data, uint32_t aConst, uint32_t shift) {\r
#if defined TRACE_MD5\r
printf("%2d: A: %08x B: %08x C: %08x D%08x\n", s_ix++ % 16, var, x, y, z);\r
printf(" K[%2d]: %08x M[?]: %08x shift: %02d\n",\r
- s_ix - 1, aConst, data, shift);\r
+ s_ix - 1, aConst, data, shift);\r
#endif\r
- rotate_left_and_add(var, var + F4(x, y, z) + data + aConst, shift, x);\r
+ rotate_left_and_add(var, var + F4(x, y, z) + data + aConst, shift, x);\r
}\r
#else\r
#define rotate_left_and_add(var, data, shift, term) { \\r
* ...\r
* </pre>\r
*/\r
-void ReMD5::processChunk(const uint8_t block[64]){\r
+void ReMD5::processChunk(const uint8_t block[64]) {\r
uint32_t M[16];\r
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15\r
#ifdef __LITTLE_ENDIAN__\r
- for (int ix = 0; ix < 16; ix++){\r
+ for (int ix = 0; ix < 16; ix++) {\r
//memcpy(&M[ix], block + ix * 4, 4);\r
- M[ix] = * (uint32_t*) (block + ix*4);\r
+ M[ix] = *(uint32_t*) (block + ix * 4);\r
}\r
#elif defined __BIG_ENDIAN__\r
- for (int ix = 0; ix < 16; ix++){\r
+ for (int ix = 0; ix < 16; ix++) {\r
uint32_t x = block[3];\r
- for (int jj = 2; jj >= 0; jj--){\r
+ for (int jj = 2; jj >= 0; jj--) {\r
x = (x << 8) + block[jj];\r
}\r
M[ix] = x;\r
\r
#endif\r
/* Round 1 */\r
- X1(A, B, C, D, M[ 0], 0xd76aa478, 7);\r
- X1(D, A, B, C, M[ 1], 0xe8c7b756, 12);\r
- X1(C, D, A, B, M[ 2], 0x242070db, 17);\r
- X1(B, C, D, A, M[ 3], 0xc1bdceee, 22);\r
- X1(A, B, C, D, M[ 4], 0xf57c0faf, 7);\r
- X1(D, A, B, C, M[ 5], 0x4787c62a, 12);\r
- X1(C, D, A, B, M[ 6], 0xa8304613, 17);\r
- X1(B, C, D, A, M[ 7], 0xfd469501, 22);\r
- X1(A, B, C, D, M[ 8], 0x698098d8, 7);\r
- X1(D, A, B, C, M[ 9], 0x8b44f7af, 12);\r
+ X1(A, B, C, D, M[0], 0xd76aa478, 7);\r
+ X1(D, A, B, C, M[1], 0xe8c7b756, 12);\r
+ X1(C, D, A, B, M[2], 0x242070db, 17);\r
+ X1(B, C, D, A, M[3], 0xc1bdceee, 22);\r
+ X1(A, B, C, D, M[4], 0xf57c0faf, 7);\r
+ X1(D, A, B, C, M[5], 0x4787c62a, 12);\r
+ X1(C, D, A, B, M[6], 0xa8304613, 17);\r
+ X1(B, C, D, A, M[7], 0xfd469501, 22);\r
+ X1(A, B, C, D, M[8], 0x698098d8, 7);\r
+ X1(D, A, B, C, M[9], 0x8b44f7af, 12);\r
X1(C, D, A, B, M[10], 0xffff5bb1, 17);\r
X1(B, C, D, A, M[11], 0x895cd7be, 22);\r
X1(A, B, C, D, M[12], 0x6b901122, 7);\r
X1(B, C, D, A, M[15], 0x49b40821, 22);\r
\r
/* Round 2 */\r
- X2 (A, B, C, D, M[ 1], 0xf61e2562, 5);\r
- X2 (D, A, B, C, M[ 6], 0xc040b340, 9);\r
- X2 (C, D, A, B, M[11], 0x265e5a51, 14);\r
- X2 (B, C, D, A, M[ 0], 0xe9b6c7aa, 20);\r
- X2 (A, B, C, D, M[ 5], 0xd62f105d, 5);\r
- X2 (D, A, B, C, M[10], 0x02441453, 9);\r
- X2 (C, D, A, B, M[15], 0xd8a1e681, 14);\r
- X2 (B, C, D, A, M[ 4], 0xe7d3fbc8, 20);\r
- X2 (A, B, C, D, M[ 9], 0x21e1cde6, 5);\r
- X2 (D, A, B, C, M[14], 0xc33707d6, 9);\r
- X2 (C, D, A, B, M[ 3], 0xf4d50d87, 14);\r
- X2 (B, C, D, A, M[ 8], 0x455a14ed, 20);\r
- X2 (A, B, C, D, M[13], 0xa9e3e905, 5);\r
- X2 (D, A, B, C, M[ 2], 0xfcefa3f8, 9);\r
- X2 (C, D, A, B, M[ 7], 0x676f02d9, 14);\r
- X2 (B, C, D, A, M[12], 0x8d2a4c8a, 20);\r
+ X2(A, B, C, D, M[1], 0xf61e2562, 5);\r
+ X2(D, A, B, C, M[6], 0xc040b340, 9);\r
+ X2(C, D, A, B, M[11], 0x265e5a51, 14);\r
+ X2(B, C, D, A, M[0], 0xe9b6c7aa, 20);\r
+ X2(A, B, C, D, M[5], 0xd62f105d, 5);\r
+ X2(D, A, B, C, M[10], 0x02441453, 9);\r
+ X2(C, D, A, B, M[15], 0xd8a1e681, 14);\r
+ X2(B, C, D, A, M[4], 0xe7d3fbc8, 20);\r
+ X2(A, B, C, D, M[9], 0x21e1cde6, 5);\r
+ X2(D, A, B, C, M[14], 0xc33707d6, 9);\r
+ X2(C, D, A, B, M[3], 0xf4d50d87, 14);\r
+ X2(B, C, D, A, M[8], 0x455a14ed, 20);\r
+ X2(A, B, C, D, M[13], 0xa9e3e905, 5);\r
+ X2(D, A, B, C, M[2], 0xfcefa3f8, 9);\r
+ X2(C, D, A, B, M[7], 0x676f02d9, 14);\r
+ X2(B, C, D, A, M[12], 0x8d2a4c8a, 20);\r
\r
/* Round 3 */\r
- X3 (A, B, C, D, M[ 5], 0xfffa3942, 4);\r
- X3 (D, A, B, C, M[ 8], 0x8771f681, 11);\r
- X3 (C, D, A, B, M[11], 0x6d9d6122, 16);\r
- X3 (B, C, D, A, M[14], 0xfde5380c, 23);\r
- X3 (A, B, C, D, M[ 1], 0xa4beea44, 4);\r
- X3 (D, A, B, C, M[ 4], 0x4bdecfa9, 11);\r
- X3 (C, D, A, B, M[ 7], 0xf6bb4b60, 16);\r
- X3 (B, C, D, A, M[10], 0xbebfbc70, 23);\r
- X3 (A, B, C, D, M[13], 0x289b7ec6, 4);\r
- X3 (D, A, B, C, M[ 0], 0xeaa127fa, 11);\r
- X3 (C, D, A, B, M[ 3], 0xd4ef3085, 16);\r
- X3 (B, C, D, A, M[ 6], 0x04881d05, 23);\r
- X3 (A, B, C, D, M[ 9], 0xd9d4d039, 4);\r
- X3 (D, A, B, C, M[12], 0xe6db99e5, 11);\r
- X3 (C, D, A, B, M[15], 0x1fa27cf8, 16);\r
- X3 (B, C, D, A, M[ 2], 0xc4ac5665, 23);\r
+ X3(A, B, C, D, M[5], 0xfffa3942, 4);\r
+ X3(D, A, B, C, M[8], 0x8771f681, 11);\r
+ X3(C, D, A, B, M[11], 0x6d9d6122, 16);\r
+ X3(B, C, D, A, M[14], 0xfde5380c, 23);\r
+ X3(A, B, C, D, M[1], 0xa4beea44, 4);\r
+ X3(D, A, B, C, M[4], 0x4bdecfa9, 11);\r
+ X3(C, D, A, B, M[7], 0xf6bb4b60, 16);\r
+ X3(B, C, D, A, M[10], 0xbebfbc70, 23);\r
+ X3(A, B, C, D, M[13], 0x289b7ec6, 4);\r
+ X3(D, A, B, C, M[0], 0xeaa127fa, 11);\r
+ X3(C, D, A, B, M[3], 0xd4ef3085, 16);\r
+ X3(B, C, D, A, M[6], 0x04881d05, 23);\r
+ X3(A, B, C, D, M[9], 0xd9d4d039, 4);\r
+ X3(D, A, B, C, M[12], 0xe6db99e5, 11);\r
+ X3(C, D, A, B, M[15], 0x1fa27cf8, 16);\r
+ X3(B, C, D, A, M[2], 0xc4ac5665, 23);\r
\r
/* Round 4 */\r
- X4 (A, B, C, D, M[ 0], 0xf4292244, 6);\r
- X4 (D, A, B, C, M[ 7], 0x432aff97, 10);\r
- X4 (C, D, A, B, M[14], 0xab9423a7, 15);\r
- X4 (B, C, D, A, M[ 5], 0xfc93a039, 21);\r
- X4 (A, B, C, D, M[12], 0x655b59c3, 6);\r
- X4 (D, A, B, C, M[ 3], 0x8f0ccc92, 10);\r
- X4 (C, D, A, B, M[10], 0xffeff47d, 15);\r
- X4 (B, C, D, A, M[ 1], 0x85845dd1, 21);\r
- X4 (A, B, C, D, M[ 8], 0x6fa87e4f, 6);\r
- X4 (D, A, B, C, M[15], 0xfe2ce6e0, 10);\r
- X4 (C, D, A, B, M[ 6], 0xa3014314, 15);\r
- X4 (B, C, D, A, M[13], 0x4e0811a1, 21);\r
- X4 (A, B, C, D, M[ 4], 0xf7537e82, 6);\r
- X4 (D, A, B, C, M[11], 0xbd3af235, 10);\r
- X4 (C, D, A, B, M[ 2], 0x2ad7d2bb, 15);\r
- X4 (B, C, D, A, M[ 9], 0xeb86d391, 21);\r
+ X4(A, B, C, D, M[0], 0xf4292244, 6);\r
+ X4(D, A, B, C, M[7], 0x432aff97, 10);\r
+ X4(C, D, A, B, M[14], 0xab9423a7, 15);\r
+ X4(B, C, D, A, M[5], 0xfc93a039, 21);\r
+ X4(A, B, C, D, M[12], 0x655b59c3, 6);\r
+ X4(D, A, B, C, M[3], 0x8f0ccc92, 10);\r
+ X4(C, D, A, B, M[10], 0xffeff47d, 15);\r
+ X4(B, C, D, A, M[1], 0x85845dd1, 21);\r
+ X4(A, B, C, D, M[8], 0x6fa87e4f, 6);\r
+ X4(D, A, B, C, M[15], 0xfe2ce6e0, 10);\r
+ X4(C, D, A, B, M[6], 0xa3014314, 15);\r
+ X4(B, C, D, A, M[13], 0x4e0811a1, 21);\r
+ X4(A, B, C, D, M[4], 0xf7537e82, 6);\r
+ X4(D, A, B, C, M[11], 0xbd3af235, 10);\r
+ X4(C, D, A, B, M[2], 0x2ad7d2bb, 15);\r
+ X4(B, C, D, A, M[9], 0xeb86d391, 21);\r
\r
//Add this chunk's hash to result so far:\r
m_a0 += A;\r
/**\r
* Prepares the instance for a new checksum.\r
*/\r
-void ReMD5::reset(){\r
+void ReMD5::reset() {\r
m_a0 = 0x67452301;\r
m_b0 = 0xefcdab89;\r
m_c0 = 0x98badcfe;\r
* @param block a block which should be added to the digest\r
* @param blockLength the length of <code>block</code>\r
*/\r
-void ReMD5::update(const uint8_t* block, int blockLength){\r
+void ReMD5::update(const uint8_t* block, int blockLength) {\r
if (blockLength == -1)\r
blockLength = strlen((const char*) block);\r
// process the "waiting" input (incomplete chunk):\r
m_length += blockLength;\r
- if (m_lengthWaiting > 0){\r
+ if (m_lengthWaiting > 0) {\r
int rest = 64 - m_lengthWaiting;\r
if (rest > blockLength)\r
rest = blockLength;\r
block += rest;\r
m_lengthWaiting += rest;\r
// Is the chunk complete?\r
- if (m_lengthWaiting == 64){\r
+ if (m_lengthWaiting == 64) {\r
processChunk(m_waiting);\r
m_lengthWaiting = 0;\r
}\r
}\r
// process full 512 bit chunks (64 byte blocks):\r
- for (int ix = blockLength / 64; ix > 0; ix--){\r
+ for (int ix = blockLength / 64; ix > 0; ix--) {\r
processChunk(block);\r
block += 64;\r
}\r
blockLength %= 64;\r
- if (blockLength != 0){\r
+ if (blockLength != 0) {\r
assert(m_lengthWaiting == 0);\r
memcpy(m_waiting, block, blockLength);\r
m_lengthWaiting = blockLength;\r
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;
* @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;
*
* @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)
* @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]);
*
* @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));
*
* @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]);
*
* @return The current character set.
*/
-ReObfuscator::CharSet ReObfuscator::getCharSet() const{
+ReObfuscator::CharSet ReObfuscator::getCharSet() const {
return m_charSet;
}
*
* @return The random generator.
*/
-ReRandomizer& ReObfuscator::getRandomizer() const{
+ReRandomizer& ReObfuscator::getRandomizer() const {
return m_rand;
}
*
* @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);
testOne(src, bufferLength, obf, rand);
}
-void testObfuscator(){
+void testObfuscator() {
ReCongruentialGenerator rand;
ReObfuscator obf(rand);
* The latest sources: https://github.com/republib
*/
-
#include "base/rebase.hpp"
#include "math/remath.hpp"
/**
* @brief Constructor.
*/
-ReRandomizer::ReRandomizer()
-{
+ReRandomizer::ReRandomizer() {
}
/**
* @brief Destructor.
}
#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.
*
* @return The next random character.
*/
-char ReRandomizer::nextChar()
-{
+char ReRandomizer::nextChar() {
char rc = nextInt(' ', ' ' + CHARRANGE - 1);
return rc;
}
*
* @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.
*
* @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;
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;
}
*
* @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;
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;
}
*
* @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;
}
*
* @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();
* @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];
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];
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;
* @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() {
}
/**
*
* @return The current factor.
*/
-ReRandomizer::seed_t ReCongruentialGenerator::factor() const
-{
- return m_factor;
+ReRandomizer::seed_t ReCongruentialGenerator::factor() const {
+ return m_factor;
}
/**
*
* @return The current increment.
*/
-ReRandomizer::seed_t ReCongruentialGenerator::increment() const
-{
- return m_increment;
+ReRandomizer::seed_t ReCongruentialGenerator::increment() const {
+ return m_increment;
}
/**
*
* @return The current seed.
*/
-ReRandomizer::seed_t ReCongruentialGenerator::seed() const
-{
- return m_seed;
+ReRandomizer::seed_t ReCongruentialGenerator::seed() const {
+ return m_seed;
}
/**
*
* Note: The constructor does the first <code>setSeed()</code>.
*/
-void ReCongruentialGenerator::reset(){
+void ReCongruentialGenerator::reset() {
m_seed = m_lastSetSeed;
}
*
* @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;
}
/**
*
* @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
* 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;
*/
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);
/** @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();
};
* 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();
seed_t m_lastSetSeed;
};
-class ReShiftRandom : public ReCongruentialGenerator {
+class ReShiftRandom: public ReCongruentialGenerator {
protected:
virtual seed_t nextSeed();
};
+++ /dev/null
-/* 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 <cstdio>
-
-
-// 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();
-}
+++ /dev/null
-/* 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 <cstring>
-#include <iostream>
-
-
-// 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
const char* ReDirTools::m_version = "2015.02.25";\r
ReLogger* ReDirTools::m_logger = NULL;\r
\r
-static const char* s_helpSummary[] = {\r
- "dirtool or dt <command> <opts>",\r
+static const char* s_helpSummary[] = { "dirtool or dt <command> <opts>",\r
" Useful commands around directory trees.",\r
- " Type 'dirtool help <command>' for more help.",\r
- "<command>:",\r
+ " Type 'dirtool help <command>' for more help.", "<command>:",\r
"batch produce output to handle the found files with a script",\r
"help shows info about the arguments/options",\r
"list shows the meta data of the selected files",\r
- "md5 shows the MD5 checksum of the selected files",\r
+ "md5 shows the MD5 checksum of the selected files",\r
"statistic shows statistics about a direcctory tree",\r
"synchronize copies only modified or new files from",\r
" from a source directory tre to a target",\r
- "touch sets the filetimes",\r
- "which finds a file in a path list (like PATH)",\r
- NULL\r
-};\r
+ "touch sets the filetimes",\r
+ "which finds a file in a path list (like PATH)",\r
+ NULL };\r
\r
const char* s_batchUsage[] = {\r
"<command>: batch [<opts>] <dir_or_file1> [<dir_or_file2> ...]",\r
" each line starts (usually) with a script name (see -c)",\r
" then it follows the full filename of the found file",\r
" use --arguments or --script to configure the output line",\r
- NULL\r
-};\r
+ NULL };\r
const char* s_batchExamples[] = {\r
"dirtool batch -cbackup.bat --basename-pattern=;*.txt;*.doc e:\\data",\r
"dirtool batch --type=r '--arguments=backup.sh !basename! !path!' usr etc",\r
- NULL\r
-};\r
+ NULL };\r
\r
const char* s_listUsage[] = {\r
"<command>: l(ist) [<opts>] <dir_or_file1> [<dir_or_file2> ...]",\r
" lists the metadata (size, modification date ...) of the selected files",\r
- NULL\r
-};\r
-const char* s_listExamples[] = {\r
- "dirtool list --min-size=10M e:\\data",\r
- "dirtool li --type=f -y7d --size=10M -p;*.cpp;*.hpp;Makefile*;-*~ /home/data",\r
- NULL\r
-};\r
+ NULL };\r
+const char* s_listExamples[] =\r
+ { "dirtool list --min-size=10M e:\\data",\r
+ "dirtool li --type=f -y7d --size=10M -p;*.cpp;*.hpp;Makefile*;-*~ /home/data",\r
+ NULL };\r
\r
const char* s_md5Usage[] = {\r
"<command>: m(d5) [<opts>] <dir_or_file1> [<dir_or_file2> ...]",\r
" shows the MD5 check sum of the given files",\r
- NULL\r
-};\r
-const char* s_md5Examples[] = {\r
- "dirtool md5 --buffer-size=512 e:\\data",\r
+ NULL };\r
+const char* s_md5Examples[] = { "dirtool md5 --buffer-size=512 e:\\data",\r
"dirtool m --type=f --size=10M -p;*.iso /home/iso /down/debian.iso",\r
- NULL\r
-};\r
-\r
-static const char* s_statisticUsage[] = {\r
- "<command>: st(atistic) [<opts>] <path1> [<path2> ...] [<depth>]",\r
- " shows a statistic about a directory tree",\r
- "<path> a directory path: relative or absolute",\r
- "<depth> 0: only the summary of <path> will be shown",\r
- " 1: shows the summery of each subdir of <path> and the total",\r
- " n: shows the summery of each subdir until level <n> and the total",\r
- " default: 1",\r
- "<opts_stat>:",\r
- NULL\r
-};\r
-const char* s_statisticExamples[] = {\r
- "dirtool st -q -t0 e:\\windows", \r
- "dirtool statistic --quiet --kbyte --trace-interval=60 ../mail ../remember 2",\r
- "dirtool stat -q --kbyte d:data 2", \r
- NULL\r
-};\r
-\r
-const char* s_syncUsage[] = {\r
- "<command>: sy(nchronize) <opts> <source1> [<source2> ...] <target>",\r
- " Synchronizes the content of a directory tree with another.",\r
- " Newer or missing files will be copied",\r
- " If a source name ends with the separator (/ in linux, \\ in win) the target",\r
- " will be completed with the basename of the source.",\r
- " Example:",\r
- " 'sync home backup' copies the file home/x.txt to backup/home/x.txt",\r
- " 'sync data/ backup/data2' copies the file home/x.txt to backup/data2/x.txt",\r
- NULL\r
-};\r
+ NULL };\r
+\r
+static const char* s_statisticUsage[] =\r
+ { "<command>: st(atistic) [<opts>] <path1> [<path2> ...] [<depth>]",\r
+ " shows a statistic about a directory tree",\r
+ "<path> a directory path: relative or absolute",\r
+ "<depth> 0: only the summary of <path> will be shown",\r
+ " 1: shows the summery of each subdir of <path> and the total",\r
+ " n: shows the summery of each subdir until level <n> and the total",\r
+ " default: 1", "<opts_stat>:",\r
+ NULL };\r
+const char* s_statisticExamples[] =\r
+ { "dirtool st -q -t0 e:\\windows",\r
+ "dirtool statistic --quiet --kbyte --trace-interval=60 ../mail ../remember 2",\r
+ "dirtool stat -q --kbyte d:data 2",\r
+ NULL };\r
+\r
+const char* s_syncUsage[] =\r
+ { "<command>: sy(nchronize) <opts> <source1> [<source2> ...] <target>",\r
+ " Synchronizes the content of a directory tree with another.",\r
+ " Newer or missing files will be copied",\r
+ " If a source name ends with the separator (/ in linux, \\ in win) the target",\r
+ " will be completed with the basename of the source.", " Example:",\r
+ " 'sync home backup' copies the file home/x.txt to backup/home/x.txt",\r
+ " 'sync data/ backup/data2' copies the file home/x.txt to backup/data2/x.txt",\r
+ NULL };\r
const char* s_syncExamples[] = {\r
"dirtool sync --basename-pattern=;*.txt;*.doc e:\\data\\ d:\\backup\\data2",\r
"dirtool sync --type=r --max-size=1G usr etc /media/backup",\r
- NULL\r
-};\r
+ NULL };\r
\r
-const char* s_touchUsage[] = {\r
- "<command>: touch [<opts>] <dir_or_file1> [<dir_or_file2> ...]",\r
- " sets the filetimes (modification and/or access time) of the selected files",\r
- NULL\r
-};\r
+const char* s_touchUsage[] =\r
+ { "<command>: touch [<opts>] <dir_or_file1> [<dir_or_file2> ...]",\r
+ " sets the filetimes (modification and/or access time) of the selected files",\r
+ NULL };\r
const char* s_touchExamples[] = {\r
"dirtool touch -p;*.csv -m2014.12.1/8:12 e:\\data e:\\history\\readme.txt",\r
- "dirtool touch -p;*.cpp --modified=now-4d12H /home/data" ,\r
- "dirtool touch -p;*.csv -m+1m . e:\\data e:\\history\\readme.txt",\r
- NULL\r
-};\r
+ "dirtool touch -p;*.cpp --modified=now-4d12H /home/data",\r
+ "dirtool touch -p;*.csv -m+1m . e:\\data e:\\history\\readme.txt",\r
+ NULL };\r
\r
const char* s_whichUsage[] = {\r
"<command>: w(hicht) [<opts>] <file_or_pattern1> [<file_or_pattern2> ...]",\r
" finds a file in a path list (like PATH)",\r
- NULL\r
-};\r
+ NULL };\r
const char* s_whichExamples[] = {\r
"dirtool which --list=JAVA_CLASSPATH org.jdom.jar *.jdom*.jar",\r
"dirtool which find.exe",\r
- NULL\r
-};\r
+ NULL };\r
/**\r
* Constructor.\r
*\r
* @param example a string vector with some examples how to use the command\r
*/\r
ReDirOptions::ReDirOptions(const char* usage[], const char* examples[]) :\r
- ReTraceUnit(INT_MAX, INT_MAX),\r
- m_programArgs(usage, examples),\r
- m_nodePatterns(),\r
- m_pathPatterns(),\r
- m_compoundUsage(NULL),\r
- m_countCompoundUsage(0),\r
- m_output(stdout),\r
- m_verboseLevel(V_NORMAL)\r
-{\r
+ ReTraceUnit(INT_MAX, INT_MAX),\r
+ m_programArgs(usage, examples),\r
+ m_nodePatterns(),\r
+ m_pathPatterns(),\r
+ m_compoundUsage(NULL),\r
+ m_countCompoundUsage(0),\r
+ m_output(stdout),\r
+ m_verboseLevel(V_NORMAL) {\r
m_nodePatterns.setIgnoreCase(true);\r
m_pathPatterns.setIgnoreCase(true);\r
}\r
/**\r
* Destructor.\r
*/\r
-ReDirOptions::~ReDirOptions(){\r
+ReDirOptions::~ReDirOptions() {\r
close();\r
delete[] m_compoundUsage;\r
}\r
* Adds a usage component to the compound usage message list.\r
* @param usage a string vector containing a part of the usage message\r
*/\r
-void ReDirOptions::addCompoundUsage(const char** usage){\r
- int start = 0;\r
- while(m_compoundUsage[start] != NULL){\r
- if (++start >= m_countCompoundUsage)\r
- assert(false);\r
- }\r
- for (int ix = 0; usage[ix] != NULL; ix++){\r
- if (start + ix > m_countCompoundUsage){\r
- assert(false);\r
- break;\r
- }\r
- m_compoundUsage[start + ix] = usage[ix];\r
- }\r
+void ReDirOptions::addCompoundUsage(const char** usage) {\r
+ int start = 0;\r
+ while (m_compoundUsage[start] != NULL) {\r
+ if (++start >= m_countCompoundUsage)\r
+ assert(false);\r
+ }\r
+ for (int ix = 0; usage[ix] != NULL; ix++) {\r
+ if (start + ix > m_countCompoundUsage) {\r
+ assert(false);\r
+ break;\r
+ }\r
+ m_compoundUsage[start + ix] = usage[ix];\r
+ }\r
}\r
\r
/**\r
* Adds the standard filter options.\r
*/\r
-void ReDirOptions::addStandardFilterOptions(){\r
+void ReDirOptions::addStandardFilterOptions() {\r
// standard short options: D d O o P p T t v y Z z\r
- m_programArgs.addInt("maxdepth",\r
- i18n("the depth of the subdirectory is lower or equal <number>\n"\r
- "0: search is done only in the base directory"),\r
- 'D', "max-depth", 512);\r
- m_programArgs.addInt("mindepth", \r
- i18n("the depth of the subdirectory is greater or equal <number>\n"\r
- "0: search is done in all subdirectories"),\r
- 'd', "min-depth", 0);\r
- m_programArgs.addString("output",\r
- i18n("the name of the output file.\n"\r
- "The output will written to this file instead of stdout"),\r
- 'O', "output-file", false, NULL);\r
- m_programArgs.addString("older",\r
- i18n("the modification date is older than <string>\n"\r
- "<string> is a date (e.g. 2015.02.17) or number followed by an unit\n"\r
- "units: m(inutes) h(hours), d(days). Default: m(inutes)\n"\r
- "examples: -o25 --older-than=30d -o24h -o2009.3.2/12:00 -o1999.01.01"),\r
- 'o', "older-than", false, NULL);\r
- m_programArgs.addString("pathpattern", \r
- i18n("a list of patterns for the path (without basename)\n"\r
- "the separator is the first character of the list\n"\r
- "Each pattern can contain '*' as wildcard\n"\r
- "If the first character is '-' the pattern is a 'not pattern':\n"\r
- "A directory will be entered if at least one of the positive patterns\n"\r
- "and none of the 'not patterns' matches\n"\r
- "examples:\n"\r
- "';music;pic*' enters music and xy/Music and PIC and pictures but not xy/pic and img\n"\r
- "';*;-.git;.hg' ignores .git and xy/z/.git and .ht"),\r
- 'P', "path-pattern", false, NULL);\r
- m_programArgs.addString("nodepattern",\r
- i18n("a list of patterns for the basename (name without path) separated by ';'\n"\r
- "Each pattern can contain '*' as wildcard\n"\r
- "If the first character is '-' the pattern is a 'not pattern':\n"\r
- "A file will be found if at least one of the positive patterns and none\n"\r
- "of the 'not patterns' matches\n"\r
- "examples: '*.cpp;*.hpp;Make*' '*;-*.bak;-*~"),\r
- 'p', "basename-pattern", false, NULL);\r
- m_programArgs.addString("verbose",\r
- i18n("verbose level: 0: no info, 1: summary only, 2: normal, 3: chatter mode, 4: debug"),\r
- 'v', "verbose", false, "1");\r
- m_programArgs.addInt("trace",\r
- i18n("all <number> seconds the current path will be traced\n"\r
- "0: no trace"),\r
- 'T', "trace-interval", 0);\r
- m_programArgs.addString("type",\r
- i18n("the file type\n"\r
- "<string> is a list of <v> values:\n"\r
- "<v>: b(lock) c(har) d(irectory) (l)i(nkdir) l(ink) o(ther)\n"\r
- " p(ipe) s(ocket) r(egular)\n"\r
- "<v>-sets: S(pecial)=bcspo N(ondir)=Slr\n"\r
- "examples: -td --type=dr -tNi"), \r
- 't', "type", false, NULL);\r
- m_programArgs.addString("younger",\r
- i18n("the modification date is younger than <string>\n"\r
- "<string> is a date (e.g. 2015.02.17) or number followed by an unit\n"\r
- "units: m(inutes) h(hours), d(days). Default: m(inutes)"),\r
- 'y', "younger-than", false, NULL);\r
- m_programArgs.addString("maxsize",\r
- i18n("the filesize is greater or equal <string>\n"\r
- "<string> is a number followed by an unit\n"\r
- "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n"\r
- "examples: -Z50m --max-size=1G"),\r
- 'Z', "max-size", false, NULL);\r
- m_programArgs.addString("minsize",\r
- i18n("the filesize is greater or equal <string>\n"\r
- "<string> is a number followed by an unit\n"\r
- "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n"\r
- "examples: -z50m --min-size=1G"),\r
- 'z', "min-size", false, NULL);\r
+ m_programArgs.addInt("maxdepth",\r
+ i18n("the depth of the subdirectory is lower or equal <number>\n"\r
+ "0: search is done only in the base directory"), 'D', "max-depth",\r
+ 512);\r
+ m_programArgs.addInt("mindepth",\r
+ i18n("the depth of the subdirectory is greater or equal <number>\n"\r
+ "0: search is done in all subdirectories"), 'd', "min-depth", 0);\r
+ m_programArgs.addString("output", i18n("the name of the output file.\n"\r
+ "The output will written to this file instead of stdout"), 'O',\r
+ "output-file", false, NULL);\r
+ m_programArgs.addString("older",\r
+ i18n(\r
+ "the modification date is older than <string>\n"\r
+ "<string> is a date (e.g. 2015.02.17) or number followed by an unit\n"\r
+ "units: m(inutes) h(hours), d(days). Default: m(inutes)\n"\r
+ "examples: -o25 --older-than=30d -o24h -o2009.3.2/12:00 -o1999.01.01"),\r
+ 'o', "older-than", false, NULL);\r
+ m_programArgs.addString("pathpattern",\r
+ i18n(\r
+ "a list of patterns for the path (without basename)\n"\r
+ "the separator is the first character of the list\n"\r
+ "Each pattern can contain '*' as wildcard\n"\r
+ "If the first character is '-' the pattern is a 'not pattern':\n"\r
+ "A directory will be entered if at least one of the positive patterns\n"\r
+ "and none of the 'not patterns' matches\n"\r
+ "examples:\n"\r
+ "';music;pic*' enters music and xy/Music and PIC and pictures but not xy/pic and img\n"\r
+ "';*;-.git;.hg' ignores .git and xy/z/.git and .ht"), 'P',\r
+ "path-pattern", false, NULL);\r
+ m_programArgs.addString("nodepattern",\r
+ i18n(\r
+ "a list of patterns for the basename (name without path) separated by ';'\n"\r
+ "Each pattern can contain '*' as wildcard\n"\r
+ "If the first character is '-' the pattern is a 'not pattern':\n"\r
+ "A file will be found if at least one of the positive patterns and none\n"\r
+ "of the 'not patterns' matches\n"\r
+ "examples: '*.cpp;*.hpp;Make*' '*;-*.bak;-*~"), 'p',\r
+ "basename-pattern", false, NULL);\r
+ m_programArgs.addString("verbose",\r
+ i18n(\r
+ "verbose level: 0: no info, 1: summary only, 2: normal, 3: chatter mode, 4: debug"),\r
+ 'v', "verbose", false, "1");\r
+ m_programArgs.addInt("trace",\r
+ i18n("all <number> seconds the current path will be traced\n"\r
+ "0: no trace"), 'T', "trace-interval", 0);\r
+ m_programArgs.addString("type", i18n("the file type\n"\r
+ "<string> is a list of <v> values:\n"\r
+ "<v>: b(lock) c(har) d(irectory) (l)i(nkdir) l(ink) o(ther)\n"\r
+ " p(ipe) s(ocket) r(egular)\n"\r
+ "<v>-sets: S(pecial)=bcspo N(ondir)=Slr\n"\r
+ "examples: -td --type=dr -tNi"), 't', "type", false, NULL);\r
+ m_programArgs.addString("younger",\r
+ i18n(\r
+ "the modification date is younger than <string>\n"\r
+ "<string> is a date (e.g. 2015.02.17) or number followed by an unit\n"\r
+ "units: m(inutes) h(hours), d(days). Default: m(inutes)"), 'y',\r
+ "younger-than", false, NULL);\r
+ m_programArgs.addString("maxsize",\r
+ i18n(\r
+ "the filesize is greater or equal <string>\n"\r
+ "<string> is a number followed by an unit\n"\r
+ "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n"\r
+ "examples: -Z50m --max-size=1G"), 'Z', "max-size", false, NULL);\r
+ m_programArgs.addString("minsize",\r
+ i18n(\r
+ "the filesize is greater or equal <string>\n"\r
+ "<string> is a number followed by an unit\n"\r
+ "units: b(yte) k(Byte) K(iByte) m(Byte), M(iByte), g(Byte) G(iByte)\n"\r
+ "examples: -z50m --min-size=1G"), 'z', "min-size", false, NULL);\r
}\r
\r
/**\r
* @return the value converted into the absolute (or relative) time\r
* @throws ReOptionExecption\r
*/\r
-ReFileTime_t ReDirOptions::checkDate(const char* value){\r
- ReByteBuffer theValue(value, -1);\r
+ReFileTime_t ReDirOptions::checkDate(const char* value) {\r
+ ReByteBuffer theValue(value, -1);\r
time_t rcTime;\r
- if (theValue.count(".") == 2){\r
- // a date:\r
- int year, month, day;\r
- int hour = 0;\r
- int minute = 0;\r
+ if (theValue.count(".") == 2) {\r
+ // a date:\r
+ int year, month, day;\r
+ int hour = 0;\r
+ int minute = 0;\r
int sec = 0;\r
- switch (sscanf(value, "%d.%d.%d/%d:%d:%d", &year, &month, &day, &hour, &minute, &sec)){\r
- case 3:\r
- case 4:\r
+ switch (sscanf(value, "%d.%d.%d/%d:%d:%d", &year, &month, &day, &hour,\r
+ &minute, &sec)) {\r
+ case 3:\r
+ case 4:\r
case 5:\r
- case 6:\r
- {\r
- if (year < 1980)\r
- throw ReOptionException(&m_programArgs, \r
- i18n("date < 1980.01.01: $1"), value);\r
- struct tm time;\r
- memset(&time, 0, sizeof time);\r
- time.tm_year = year - 1900;\r
- time.tm_mon = month - 1;\r
- time.tm_mday = day;\r
- time.tm_hour = hour;\r
- time.tm_min = minute;\r
+ case 6: {\r
+ if (year < 1980)\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n("date < 1980.01.01: $1"), value);\r
+ struct tm time;\r
+ memset(&time, 0, sizeof time);\r
+ time.tm_year = year - 1900;\r
+ time.tm_mon = month - 1;\r
+ time.tm_mday = day;\r
+ time.tm_hour = hour;\r
+ time.tm_min = minute;\r
time.tm_sec = sec;\r
- rcTime = mktime(&time);\r
- break;\r
- }\r
- default:\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid date/date-time value: $1 yyyy.mm.dd/hh:MM expected"), value);\r
- }\r
- } else if (theValue.count(":") >= 1){\r
- // a time:\r
- int hour = 0;\r
- int minute = 0;\r
+ rcTime = mktime(&time);\r
+ break;\r
+ }\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n(\r
+ "invalid date/date-time value: $1 yyyy.mm.dd/hh:MM expected"),\r
+ value);\r
+ }\r
+ } else if (theValue.count(":") >= 1) {\r
+ // a time:\r
+ int hour = 0;\r
+ int minute = 0;\r
int sec = 0;\r
- switch (sscanf(value, "%d:%d:%d", &hour, &minute, &sec)){\r
- case 2:\r
- case 3:\r
- {\r
+ switch (sscanf(value, "%d:%d:%d", &hour, &minute, &sec)) {\r
+ case 2:\r
+ case 3: {\r
// the time (today)\r
- rcTime = time(NULL) / 86400 * 86400 + hour * 3600 + minute * 60 + sec;\r
- break;\r
- }\r
- default:\r
- throw ReOptionException(&m_programArgs,\r
- i18n("invalid time value: $1. HH:MM:SS expected"), value);\r
- }\r
- } else {\r
- // a time distance value:\r
- char unit = 'm';\r
- int count = 0;\r
+ rcTime = time(NULL) / 86400 * 86400 + hour * 3600 + minute * 60\r
+ + sec;\r
+ break;\r
+ }\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n("invalid time value: $1. HH:MM:SS expected"), value);\r
+ }\r
+ } else {\r
+ // a time distance value:\r
+ char unit = 'm';\r
+ int count = 0;\r
int negativeFactor = 1;\r
bool fromNow = theValue.startsWith("now");\r
- if (fromNow){\r
+ if (fromNow) {\r
theValue.remove(0, 3);\r
}\r
char cc = theValue.at(0);\r
- if (cc == '-' || cc == '+'){\r
+ if (cc == '-' || cc == '+') {\r
if (cc == '-')\r
negativeFactor = -1;\r
theValue.remove(0, 1);\r
}\r
- switch(sscanf(theValue.str(), "%d%c", &count, &unit)){\r
- case 1:\r
- case 2:\r
- switch(unit){\r
+ switch (sscanf(theValue.str(), "%d%c", &count, &unit)) {\r
+ case 1:\r
+ case 2:\r
+ switch (unit) {\r
case 's':\r
break;\r
- case 'm':\r
- count *= 60;\r
- break;\r
- case 'h':\r
- count *= 60*60;\r
- break;\r
- case 'd':\r
- count *= 24*60*60;\r
- break;\r
- default:\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid unit $1. expected: s(econds) m(inutes) h(ours) d(ays)"), value);\r
- }\r
- rcTime = count * negativeFactor;\r
- break;\r
- default:\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid relative time value $1 (<number><unit> expected). <unit>: s m h d"),\r
- value);\r
- }\r
- if (fromNow)\r
+ case 'm':\r
+ count *= 60;\r
+ break;\r
+ case 'h':\r
+ count *= 60 * 60;\r
+ break;\r
+ case 'd':\r
+ count *= 24 * 60 * 60;\r
+ break;\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n(\r
+ "invalid unit $1. expected: s(econds) m(inutes) h(ours) d(ays)"),\r
+ value);\r
+ }\r
+ rcTime = count * negativeFactor;\r
+ break;\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n(\r
+ "invalid relative time value $1 (<number><unit> expected). <unit>: s m h d"),\r
+ value);\r
+ }\r
+ if (fromNow)\r
rcTime += time(NULL);\r
- }\r
- ReFileTime_t rc;\r
+ }\r
+ ReFileTime_t rc;\r
ReDirStatus_t::timeToFiletime(rcTime, rc);\r
- return rc;\r
+ return rc;\r
}\r
/**\r
* Checks whether the given value is a time expression.\r
* @return the value (multiplied with the unit factor)\r
* @throws ReOptionExecption\r
*/\r
-time_t ReDirOptions::checkSize(const char* value){\r
- int64_t rc = 0;\r
- char unit = 'b';\r
- switch (sscanf(value, "%lld%c", (long long int*) &rc, &unit)){\r
- case 1:\r
- case 2:\r
- switch(unit){\r
- case 'b':\r
- break;\r
- case 'k':\r
- rc *= 1000;\r
- break;\r
- case 'K':\r
- rc *= 1024;\r
- break;\r
- case 'm':\r
- rc *= 1000*1000;\r
- break;\r
- case 'M':\r
- rc *= 1024*1024;\r
- break;\r
- case 'g':\r
- rc *= 1000LL*1000*1000;\r
- break;\r
- case 'G':\r
- rc *= 1024LL*1024*1024;\r
- break;\r
- default:\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid <unit>: $1. Expected: b k K m M g G"),\r
- value);\r
- }\r
- break;\r
- default:\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid size value: $1 expected: <number><unit> <unit>: b k K m M g G"),\r
- value);\r
- }\r
- return rc;\r
+time_t ReDirOptions::checkSize(const char* value) {\r
+ int64_t rc = 0;\r
+ char unit = 'b';\r
+ switch (sscanf(value, "%lld%c", (long long int*) &rc, &unit)) {\r
+ case 1:\r
+ case 2:\r
+ switch (unit) {\r
+ case 'b':\r
+ break;\r
+ case 'k':\r
+ rc *= 1000;\r
+ break;\r
+ case 'K':\r
+ rc *= 1024;\r
+ break;\r
+ case 'm':\r
+ rc *= 1000 * 1000;\r
+ break;\r
+ case 'M':\r
+ rc *= 1024 * 1024;\r
+ break;\r
+ case 'g':\r
+ rc *= 1000LL * 1000 * 1000;\r
+ break;\r
+ case 'G':\r
+ rc *= 1024LL * 1024 * 1024;\r
+ break;\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n("invalid <unit>: $1. Expected: b k K m M g G"), value);\r
+ }\r
+ break;\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n(\r
+ "invalid size value: $1 expected: <number><unit> <unit>: b k K m M g G"),\r
+ value);\r
+ }\r
+ return rc;\r
}\r
/**\r
* Checks whether the given value is a valid pattern list.\r
* @return the <cpde>value</code> (for chaining)\r
* @throws ReOptionExecption\r
*/\r
-const char* ReDirOptions::checkPatternList(const char* value){\r
- if (isalnum(*value) || *value == '_' || *value == '*'\r
- || *value == '.' || *value == '-')\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid separator (first character): $1 use ';' instead"), \r
- value);\r
+const char* ReDirOptions::checkPatternList(const char* value) {\r
+ if (isalnum(*value) || *value == '_' || *value == '*' || *value == '.'\r
+ || *value == '-')\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n("invalid separator (first character): $1 use ';' instead"),\r
+ value);\r
if (strchr(value, OS_SEPARATOR_CHAR) != NULL)\r
- throw ReOptionException(&m_programArgs, \r
- i18n("slash not allowed in pattern list: $1"), value);\r
- return value;\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n("slash not allowed in pattern list: $1"), value);\r
+ return value;\r
}\r
/**\r
* Checks whether the given value is a valid filetype list.\r
* @return the bitmask\r
* @throws ReOptionExecption\r
*/\r
-ReDirStatus_t::Type_t ReDirOptions::checkType(const char* value){\r
- int rc = ReDirStatus_t::TF_UNDEF;\r
- while (*value != '\0'){\r
- switch(*value){\r
- case 'b':\r
- rc |= ReDirStatus_t::TF_BLOCK;\r
- break;\r
- case 'c':\r
- rc |= ReDirStatus_t::TF_CHAR;\r
- break;\r
- case 'd':\r
- rc |= ReDirStatus_t::TF_SUBDIR;\r
- break;\r
- case 'i':\r
- rc |= ReDirStatus_t::TF_LINK_DIR;\r
- break;\r
- case 'l':\r
- rc |= ReDirStatus_t::TF_LINK;\r
- break;\r
- case 'o':\r
- rc |= ReDirStatus_t::TF_OTHER;\r
- break;\r
- case 'p':\r
- rc |= ReDirStatus_t::TF_PIPE;\r
- break;\r
- case 's':\r
- rc |= ReDirStatus_t::TF_SOCKET;\r
- break;\r
- case 'r':\r
- rc |= ReDirStatus_t::TF_REGULAR;\r
- break;\r
- case 'S':\r
- rc |= ReDirStatus_t::TC_SPECIAL;\r
- break;\r
- case 'N':\r
- rc |= ReDirStatus_t::TC_NON_DIR;\r
- break;\r
- case ' ':\r
- case ',':\r
- break;\r
- default:\r
- throw ReOptionException(&m_programArgs, \r
- i18n("invalid type: $1 Expected: b(lock) c(har) d(irectory)"\r
- " (l)i(nkdir) l(ink) o(ther) p(ipe) s(ocket) r(egular)"\r
- " S(pecial=bcspo) N(ondir=Slr)"), \r
- value);\r
- }\r
- value++;\r
- }\r
- return (ReDirStatus_t::Type_t) rc;\r
+ReDirStatus_t::Type_t ReDirOptions::checkType(const char* value) {\r
+ int rc = ReDirStatus_t::TF_UNDEF;\r
+ while (*value != '\0') {\r
+ switch (*value) {\r
+ case 'b':\r
+ rc |= ReDirStatus_t::TF_BLOCK;\r
+ break;\r
+ case 'c':\r
+ rc |= ReDirStatus_t::TF_CHAR;\r
+ break;\r
+ case 'd':\r
+ rc |= ReDirStatus_t::TF_SUBDIR;\r
+ break;\r
+ case 'i':\r
+ rc |= ReDirStatus_t::TF_LINK_DIR;\r
+ break;\r
+ case 'l':\r
+ rc |= ReDirStatus_t::TF_LINK;\r
+ break;\r
+ case 'o':\r
+ rc |= ReDirStatus_t::TF_OTHER;\r
+ break;\r
+ case 'p':\r
+ rc |= ReDirStatus_t::TF_PIPE;\r
+ break;\r
+ case 's':\r
+ rc |= ReDirStatus_t::TF_SOCKET;\r
+ break;\r
+ case 'r':\r
+ rc |= ReDirStatus_t::TF_REGULAR;\r
+ break;\r
+ case 'S':\r
+ rc |= ReDirStatus_t::TC_SPECIAL;\r
+ break;\r
+ case 'N':\r
+ rc |= ReDirStatus_t::TC_NON_DIR;\r
+ break;\r
+ case ' ':\r
+ case ',':\r
+ break;\r
+ default:\r
+ throw ReOptionException(&m_programArgs,\r
+ i18n("invalid type: $1 Expected: b(lock) c(har) d(irectory)"\r
+ " (l)i(nkdir) l(ink) o(ther) p(ipe) s(ocket) r(egular)"\r
+ " S(pecial=bcspo) N(ondir=Slr)"), value);\r
+ }\r
+ value++;\r
+ }\r
+ return (ReDirStatus_t::Type_t) rc;\r
}\r
\r
/**\r
* @param message2 an additional message\r
*/\r
\r
-void ReDirOptions::help(const char* errorMessage, const char* message2) const{\r
- ReByteBuffer msg;\r
- if (errorMessage != 0)\r
- msg.append(errorMessage, -1);\r
- if (message2 != NULL)\r
- msg.append(message2, -1);\r
- m_programArgs.help(msg.str(), false, stdout);\r
- exit(1);\r
+void ReDirOptions::help(const char* errorMessage, const char* message2) const {\r
+ ReByteBuffer msg;\r
+ if (errorMessage != 0)\r
+ msg.append(errorMessage, -1);\r
+ if (message2 != NULL)\r
+ msg.append(message2, -1);\r
+ m_programArgs.help(msg.str(), false, stdout);\r
+ exit(1);\r
}\r
\r
/**\r
* \r
* @throws \r
*/\r
-void ReDirOptions::checkStandardFilterOptions(){\r
- ReByteBuffer buffer;\r
- if (m_programArgs.getString("older", buffer)[0] != '\0')\r
- checkDate(buffer.str());\r
- if (m_programArgs.getString("younger", buffer)[0] != '\0')\r
- checkDate(buffer.str());\r
- if (m_programArgs.getString("type", buffer)[0] != '\0')\r
- checkType(buffer.str());\r
- if (m_programArgs.getString("maxsize", buffer)[0] != '\0')\r
- checkSize(buffer.str());\r
- if (m_programArgs.getString("minsize", buffer)[0] != '\0')\r
- checkSize(buffer.str());\r
- if (m_programArgs.getString("nodepattern", buffer)[0] != '\0')\r
- checkPatternList(buffer.str());\r
- if (m_programArgs.getString("pathpattern", buffer)[0] != '\0')\r
- checkPatternList(buffer.str());\r
- if (m_programArgs.getString("verbose", buffer)[0] != '\0'){\r
+void ReDirOptions::checkStandardFilterOptions() {\r
+ ReByteBuffer buffer;\r
+ if (m_programArgs.getString("older", buffer)[0] != '\0')\r
+ checkDate(buffer.str());\r
+ if (m_programArgs.getString("younger", buffer)[0] != '\0')\r
+ checkDate(buffer.str());\r
+ if (m_programArgs.getString("type", buffer)[0] != '\0')\r
+ checkType(buffer.str());\r
+ if (m_programArgs.getString("maxsize", buffer)[0] != '\0')\r
+ checkSize(buffer.str());\r
+ if (m_programArgs.getString("minsize", buffer)[0] != '\0')\r
+ checkSize(buffer.str());\r
+ if (m_programArgs.getString("nodepattern", buffer)[0] != '\0')\r
+ checkPatternList(buffer.str());\r
+ if (m_programArgs.getString("pathpattern", buffer)[0] != '\0')\r
+ checkPatternList(buffer.str());\r
+ if (m_programArgs.getString("verbose", buffer)[0] != '\0') {\r
unsigned level = V_NORMAL;\r
if (ReStringUtils::lengthOfUnsigned(buffer.str(), -1, &level)\r
- != buffer.length())\r
+ != buffer.length())\r
help(i18n("verbose level is not a number (or '')"), buffer.str());\r
else\r
m_verboseLevel = VerboseLevel(level);\r
/**\r
* Frees the resources.\r
*/\r
-void ReDirOptions::close(){\r
- if (m_output != stdout && m_output != stderr){\r
+void ReDirOptions::close() {\r
+ if (m_output != stdout && m_output != stderr) {\r
fclose(m_output);\r
}\r
m_output = stdout;\r
*\r
* @param size the size of the array: size = (field1 + field2 + ...) * sizeof(const char*)\r
*/\r
-void ReDirOptions::initCompoundUsage(size_t size){\r
- delete[] m_compoundUsage;\r
- int count = size / sizeof m_compoundUsage[0];\r
- m_compoundUsage = new const char*[count];\r
- memset(m_compoundUsage, 0, size);\r
- m_countCompoundUsage = count;\r
+void ReDirOptions::initCompoundUsage(size_t size) {\r
+ delete[] m_compoundUsage;\r
+ int count = size / sizeof m_compoundUsage[0];\r
+ m_compoundUsage = new const char*[count];\r
+ memset(m_compoundUsage, 0, size);\r
+ m_countCompoundUsage = count;\r
}\r
\r
/**\r
*\r
* @param buffer the pattern list as string, e.g. ";*;-cache"\r
*/\r
-void ReDirOptions::optimizePathPattern(ReByteBuffer& buffer){\r
+void ReDirOptions::optimizePathPattern(ReByteBuffer& buffer) {\r
ReStringList list;\r
ReStringList rootList;\r
list.split(buffer.str() + 1, buffer.str()[0]);\r
buffer.replaceAll(OS_SEPARATOR, 1, "/", 1);\r
ReByteBuffer item;\r
- for (int ix = 0; ix < (int) list.count(); ix++){\r
+ for (int ix = 0; ix < (int) list.count(); ix++) {\r
item.set(list.strOf(ix), -1);\r
if (item.endsWith("/*"))\r
item.setLength(item.length() - 2);\r
bool notAnchored = item.startsWith("*/") || item.startsWith("-*/");\r
item.replaceAll("/", 1, OS_SEPARATOR, 1);\r
list.replace(ix, item.str());\r
- if (notAnchored){\r
+ if (notAnchored) {\r
item.remove(item.str()[0] == '-' ? 1 : 0, 2);\r
rootList.append(item.str(), 0);\r
}\r
}\r
- if (rootList.count() > 0){\r
+ if (rootList.count() > 0) {\r
list.append(rootList);\r
}\r
item.set(buffer.str(), 1);\r
*\r
* @param filter OUT: the filter to set\r
*/\r
-void ReDirOptions::setFilterFromProgramArgs(ReDirEntryFilter_t& filter){\r
- ReByteBuffer buffer;\r
- if (m_programArgs.getString("younger", buffer)[0] != '\0')\r
- filter.m_maxAge = checkDate(buffer.str());\r
- if (m_programArgs.getString("older", buffer)[0] != '\0')\r
- filter.m_minAge = checkDate(buffer.str());\r
- if (m_programArgs.getString("maxsize", buffer)[0] != '\0')\r
- filter.m_maxSize = checkSize(buffer.str());\r
- if (m_programArgs.getString("minsize", buffer)[0] != '\0')\r
- filter.m_minSize = checkSize(buffer.str());\r
- if (m_programArgs.getString("type", buffer)[0] != '\0')\r
- filter.m_types = checkType(buffer.str());\r
- filter.m_minDepth = m_programArgs.getInt("mindepth");\r
- filter.m_maxDepth = m_programArgs.getInt("maxdepth");\r
- if (m_programArgs.getString("nodepattern", buffer)[0] != '\0'){\r
- checkPatternList(buffer.str());\r
- m_nodePatterns.set(buffer.str());\r
- filter.m_nodePatterns = &m_nodePatterns;\r
- }\r
- if (m_programArgs.getString("pathpattern", buffer)[0] != '\0'){\r
- checkPatternList(buffer.str());\r
+void ReDirOptions::setFilterFromProgramArgs(ReDirEntryFilter_t& filter) {\r
+ ReByteBuffer buffer;\r
+ if (m_programArgs.getString("younger", buffer)[0] != '\0')\r
+ filter.m_maxAge = checkDate(buffer.str());\r
+ if (m_programArgs.getString("older", buffer)[0] != '\0')\r
+ filter.m_minAge = checkDate(buffer.str());\r
+ if (m_programArgs.getString("maxsize", buffer)[0] != '\0')\r
+ filter.m_maxSize = checkSize(buffer.str());\r
+ if (m_programArgs.getString("minsize", buffer)[0] != '\0')\r
+ filter.m_minSize = checkSize(buffer.str());\r
+ if (m_programArgs.getString("type", buffer)[0] != '\0')\r
+ filter.m_types = checkType(buffer.str());\r
+ filter.m_minDepth = m_programArgs.getInt("mindepth");\r
+ filter.m_maxDepth = m_programArgs.getInt("maxdepth");\r
+ if (m_programArgs.getString("nodepattern", buffer)[0] != '\0') {\r
+ checkPatternList(buffer.str());\r
+ m_nodePatterns.set(buffer.str());\r
+ filter.m_nodePatterns = &m_nodePatterns;\r
+ }\r
+ if (m_programArgs.getString("pathpattern", buffer)[0] != '\0') {\r
+ checkPatternList(buffer.str());\r
optimizePathPattern(buffer);\r
- m_pathPatterns.set(buffer.str());\r
- filter.m_pathPatterns = &m_pathPatterns;\r
- }\r
- if ( (m_interval = m_programArgs.getInt("trace")) != 0)\r
+ m_pathPatterns.set(buffer.str());\r
+ filter.m_pathPatterns = &m_pathPatterns;\r
+ }\r
+ if ((m_interval = m_programArgs.getInt("trace")) != 0)\r
m_triggerCount = 10;\r
- if (m_programArgs.getString("output", buffer)[0] != '\0'){\r
- if ( (m_output = fopen(buffer.str(), "w")) == NULL){\r
+ if (m_programArgs.getString("output", buffer)[0] != '\0') {\r
+ if ((m_output = fopen(buffer.str(), "w")) == NULL) {\r
help("cannot open output file", buffer.str());\r
m_output = stdout;\r
}\r
* directory will be added as argument\r
* @param logger logger for error messages\r
*/\r
-ReTool::ReTool(const char* usage[], const char* example[],\r
- int minArguments, int reservedFirst, int reservedLast,\r
- bool addCurrentDirIfNoArguments, ReLogger* logger) :\r
- ReDirOptions(usage, example),\r
- ReDirTreeStatistic(),\r
- m_minArguments(minArguments),\r
- m_reservedFirst(reservedFirst),\r
- m_reservedLast(reservedLast),\r
- m_addCurrentDirIfNoArguments(addCurrentDirIfNoArguments),\r
- m_hasStandardArgs(true),\r
- m_traverser(NULL, this, logger),\r
- m_filter(),\r
- m_start(time(NULL)),\r
- m_logger(logger)\r
-{\r
+ReTool::ReTool(const char* usage[], const char* example[], int minArguments,\r
+ int reservedFirst, int reservedLast, bool addCurrentDirIfNoArguments,\r
+ ReLogger* logger) :\r
+ ReDirOptions(usage, example),\r
+ ReDirTreeStatistic(),\r
+ m_minArguments(minArguments),\r
+ m_reservedFirst(reservedFirst),\r
+ m_reservedLast(reservedLast),\r
+ m_addCurrentDirIfNoArguments(addCurrentDirIfNoArguments),\r
+ m_hasStandardArgs(true),\r
+ m_traverser(NULL, this, logger),\r
+ m_filter(),\r
+ m_start(time(NULL)),\r
+ m_logger(logger) {\r
}\r
\r
/**\r
* Destructor.\r
*/\r
-ReTool::~ReTool(){\r
+ReTool::~ReTool() {\r
}\r
\r
/**\r
* @param currentFile message for the trace\r
* @return <code>true</code> (for chaining)\r
*/\r
-bool ReTool::trace(const char* currentFile){\r
+bool ReTool::trace(const char* currentFile) {\r
ReByteBuffer buffer(" ");\r
int duration = int(time(NULL) - m_startTime);\r
buffer.appendInt(duration / 60).appendInt(duration % 60, ":%02d: ");\r
- buffer.appendInt(m_files).appendChar('/').appendInt(m_traverser.directories()).append(" dir(s)");\r
- buffer.appendInt(m_files).appendChar('/').appendInt(m_traverser.files()).append(" file(s)");\r
+ buffer.appendInt(m_files).appendChar('/').appendInt(\r
+ m_traverser.directories()).append(" dir(s)");\r
+ buffer.appendInt(m_files).appendChar('/').appendInt(m_traverser.files())\r
+ .append(" file(s)");\r
buffer.append(currentFile);\r
fputs(buffer.str(), stdout);\r
return true;\r
* @param argv program arguments\r
* @param minArguments the command needs at least so many non option arguments\r
*/\r
-void ReTool::run(int argc, const char** argv){\r
+void ReTool::run(int argc, const char** argv) {\r
try {\r
m_programArgs.init(argc, argv);\r
if (m_programArgs.getArgCount() < m_minArguments)\r
m_programArgs.help(i18n("too few arguments"), false, stdout);\r
if (m_hasStandardArgs)\r
- setFilterFromProgramArgs(m_filter);\r
+ setFilterFromProgramArgs(m_filter);\r
doIt();\r
- if (m_output != stdout){\r
+ if (m_output != stdout) {\r
fclose(m_output);\r
m_output = stdout;\r
}\r
- \r
- } catch (ReOptionException& exc) {\r
- m_programArgs.help(exc.getMessage(), false, stdout);\r
- }\r
+\r
+ } catch (ReOptionException& exc) {\r
+ m_programArgs.help(exc.getMessage(), false, stdout);\r
+ }\r
}\r
/**\r
* Evaluates the non option arguments which are names of files or directories.\r
* or <code>processTree()</code>.\r
*\r
*/\r
-void ReTool::processFileArguments(){\r
+void ReTool::processFileArguments() {\r
int max = m_programArgs.getArgCount() - m_reservedLast;\r
// Test whether the arguments are files or directories:\r
ReByteBuffer arg;\r
- for (int ii = m_reservedFirst; ii < max; ii++){\r
+ for (int ii = m_reservedFirst; ii < max; ii++) {\r
arg = m_programArgs.getArg(ii);\r
- if (! exists(arg) != 0)\r
+ if (!exists(arg) != 0)\r
m_programArgs.help(\r
- ReByteBuffer(i18n("not a file or a directory: ")).append(arg).str(),\r
- false, stderr);\r
+ ReByteBuffer(i18n("not a file or a directory: ")).append(arg)\r
+ .str(), false, stderr);\r
}\r
// process the files:\r
- for (int ii = m_reservedFirst; ii < max; ii++){\r
+ for (int ii = m_reservedFirst; ii < max; ii++) {\r
const char* arg = m_programArgs.getArg(ii);\r
if (S_ISDIR(m_statInfo.st_mode))\r
processTree(arg);\r
*\r
* @param filename the name of the file\r
*/\r
-void ReTool::processSingleFile(const char* filename){\r
+void ReTool::processSingleFile(const char* filename) {\r
ReByteBuffer protocol;\r
ReByteBuffer path;\r
ReByteBuffer name;\r
m_traverser.setPropertiesFromFilter(&m_filter);\r
ReDirStatus_t entry(m_logger);\r
entry.m_path = protocol;\r
- if (entry.findFirst()){\r
+ if (entry.findFirst()) {\r
do {\r
#if defined __linux__\r
bool found = strcmp(entry.node(), name.str()) == 0;\r
#elif defined __WIN32__\r
bool found = _stricmp(entry.node(), name.str()) == 0;\r
#endif\r
- if (found && m_filter.match(entry)){\r
+ if (found && m_filter.match(entry)) {\r
processFile(&entry);\r
break;\r
}\r
- } while(entry.findNext());\r
+ } while (entry.findNext());\r
}\r
entry.freeEntry();\r
}\r
*\r
* @param directory the name of the directory\r
*/\r
-void ReTool::processTree(const char* directory){\r
+void ReTool::processTree(const char* directory) {\r
m_traverser.changeBase(directory);\r
m_traverser.setPropertiesFromFilter(&m_filter);\r
ReDirStatus_t* entry;\r
int level;\r
- while( (entry = m_traverser.nextFile(level, &m_filter)) != NULL){\r
- if (entry->isDirectory()){\r
+ while ((entry = m_traverser.nextFile(level, &m_filter)) != NULL) {\r
+ if (entry->isDirectory()) {\r
processDir(entry);\r
m_directories++;\r
} else {\r
*\r
* @param entry the properties of the file to process\r
*/\r
-void ReTool::processFile(ReDirStatus_t* entry){\r
+void ReTool::processFile(ReDirStatus_t* entry) {\r
fprintf(m_output, "+++ ignored (not a directory): %s\n", entry->fullName());\r
}\r
/**\r
* \r
* @param prefix NULL or a line prefix\r
*/\r
-void ReTool::printSummary(const char* prefix){\r
- if (m_verboseLevel >= V_SUMMARY){\r
+void ReTool::printSummary(const char* prefix) {\r
+ if (m_verboseLevel >= V_SUMMARY) {\r
int duration = int(time(NULL) - m_start);\r
ReByteBuffer line;\r
ReByteBuffer line2;\r
statisticAsString(line);\r
- double rate = duration == 0 ? 0.0 : (m_files + m_directories) / duration;\r
+ double rate =\r
+ duration == 0 ? 0.0 : (m_files + m_directories) / duration;\r
line.append(rate, " %.1f").append(i18n("/sec"), -1);\r
m_traverser.statisticAsString(line2);\r
- line2.appendChar(' ').appendTime(duration).append(" ", 1).append(i18n("sec"));\r
- fprintf(m_output, "%s=== filtered: %s\n", prefix == NULL ? "" : prefix, line.str());\r
- fprintf(m_output, "%s=== total: %s\n", prefix == NULL ? "" : prefix, line2.str());\r
+ line2.appendChar(' ').appendTime(duration).append(" ", 1).append(\r
+ i18n("sec"));\r
+ fprintf(m_output, "%s=== filtered: %s\n", prefix == NULL ? "" : prefix,\r
+ line.str());\r
+ fprintf(m_output, "%s=== total: %s\n", prefix == NULL ? "" : prefix,\r
+ line2.str());\r
}\r
\r
}\r
*\r
* @param entry the properties of the directory to process\r
*/\r
-void ReTool::processDir(ReDirStatus_t* entry){\r
+void ReTool::processDir(ReDirStatus_t* entry) {\r
fprintf(m_output, "+++ ignored (not a file): %s\n", entry->fullName());\r
}\r
\r
* Constructor.\r
*/\r
ReDirStatisticData::ReDirStatisticData() :\r
- ReDirTreeStatistic(),\r
- m_path()\r
-{\r
+ ReDirTreeStatistic(),\r
+ m_path() {\r
}\r
/**\r
* Copy constructor.\r
* @param source the source to copy\r
*/\r
ReDirStatisticData::ReDirStatisticData(const ReDirStatisticData& source) :\r
- m_path(source.m_path)\r
-{\r
+ m_path(source.m_path) {\r
}\r
/**\r
* Assignment operator.\r
* @param source the source to copy\r
* @return the instance itself\r
*/\r
-ReDirStatisticData& ReDirStatisticData::operator =(const ReDirStatisticData& source){\r
+ReDirStatisticData& ReDirStatisticData::operator =(\r
+ const ReDirStatisticData& source) {\r
m_sizes = source.m_sizes;\r
m_files = source.m_files;\r
m_directories = source.m_directories;\r
* @param deltaBuffer increment if content buffer must be increased\r
*/\r
ReDirStatistic::ReDirStatistic(ReLogger* logger, int deltaList, int deltaBuffer) :\r
- ReTool(s_statisticUsage, s_statisticExamples, 2, 0, 1, false, logger),\r
- m_list(deltaList, deltaBuffer)\r
-{\r
+ ReTool(s_statisticUsage, s_statisticExamples, 2, 0, 1, false, logger),\r
+ m_list(deltaList, deltaBuffer) {\r
// standard short options: D d O o P p T t v y Z z\r
- m_programArgs.addBool("kbyte", \r
- i18n("output format is '<kbyte> <path>' (like unix 'du' command)"),\r
- 'k', "kbyte", false);\r
- addStandardFilterOptions();\r
+ m_programArgs.addBool("kbyte",\r
+ i18n("output format is '<kbyte> <path>' (like unix 'du' command)"), 'k',\r
+ "kbyte", false);\r
+ addStandardFilterOptions();\r
}\r
/**\r
* Destructor.\r
*/\r
-ReDirStatistic::~ReDirStatistic(){\r
+ReDirStatistic::~ReDirStatistic() {\r
}\r
\r
/**\r
* @param source the other instance\r
* @return the instance itself\r
*/\r
-ReDirStatisticData& ReDirStatisticData::add(const ReDirStatisticData& source){\r
+ReDirStatisticData& ReDirStatisticData::add(const ReDirStatisticData& source) {\r
m_sizes += source.m_sizes;\r
m_files += source.m_files;\r
m_directories += source.m_directories;\r
/**\r
* Initializes the data of the instance.\r
*/\r
-void ReDirStatisticData::clear(){\r
+void ReDirStatisticData::clear() {\r
ReDirTreeStatistic::clear();\r
m_path.setLength(0);\r
}\r
* @param logger logger for error handling\r
*/\r
ReDirBatch::ReDirBatch(ReLogger* logger) :\r
- ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger),\r
- m_arguments(),\r
- m_script(),\r
- m_isExe(false)\r
-{\r
+ ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger),\r
+ m_arguments(),\r
+ m_script(),\r
+ m_isExe(false) {\r
// standard short options: D d O o P p T t v y Z z\r
- m_programArgs.addString("first",\r
- i18n("defines the first line of the output"),\r
- '1', "first-line", true,\r
+ m_programArgs.addString("first",\r
+ i18n("defines the first line of the output"),\r
+ '1', "first-line", true,\r
#if defined __linux__\r
- "#! /bin/sh"\r
+ "#! /bin/sh"\r
#elif defined __WIN32__\r
- "rem this batch is created by dirtool"\r
+ "rem this batch is created by dirtool"\r
#endif\r
- );\r
- m_programArgs.addString("arguments",\r
- i18n("template for the output line.\n"\r
- "Possible placeholders: (e.g. e:\\data\\sample.txt)\n"\r
- " !full!: e:\\data\\sample.txt\n"\r
- " !path!: e:\\data\\\n"\r
- " !basename!: sample.txt\n"\r
- " !name!: sample\n"\r
- " !ext!: .txt\n"\r
- "example: --arguments='echo !basename! in !path! found'"),\r
- 'a', "arguments", false, NULL);\r
- m_programArgs.addString("script",\r
- i18n("name of the script (starts each output line)"),\r
- 'c', "script", false, NULL);\r
+ );\r
+ m_programArgs.addString("arguments", i18n("template for the output line.\n"\r
+ "Possible placeholders: (e.g. e:\\data\\sample.txt)\n"\r
+ " !full!: e:\\data\\sample.txt\n"\r
+ " !path!: e:\\data\\\n"\r
+ " !basename!: sample.txt\n"\r
+ " !name!: sample\n"\r
+ " !ext!: .txt\n"\r
+ "example: --arguments='echo !basename! in !path! found'"), 'a',\r
+ "arguments", false, NULL);\r
+ m_programArgs.addString("script",\r
+ i18n("name of the script (starts each output line)"), 'c', "script",\r
+ false, NULL);\r
#if defined __WIN32__\r
- m_programArgs.addBool("isexe",\r
- i18n("supresses the starting 'call' of each output line"\r
- "neccessary if a *.exe will be called (instead of a *.bat)"),\r
- 'x', "is-exe", false);\r
+ m_programArgs.addBool("isexe",\r
+ i18n("supresses the starting 'call' of each output line"\r
+ "neccessary if a *.exe will be called (instead of a *.bat)"),\r
+ 'x', "is-exe", false);\r
#endif\r
- addStandardFilterOptions();\r
-}\r
-\r
-static void replaceMakros(const char* arguments, ReDirStatus_t* entry, const char* delim, ReByteBuffer& line){\r
- line.set(arguments, -1);\r
- // we prepare the removal of unwanted delimiters in constructed placeholders:\r
- // example: !path!!name!: without correction: "e:\\data\\""xxx"\r
- // We want: "e:\\data\\xxx"\r
- line.replaceAll("!!", 2, "!\x01!", 3);\r
- ReByteBuffer replacement;\r
- if (strstr(arguments, "!full!") != NULL){\r
- replacement.set(delim, -1).append(entry->m_path);\r
- replacement.append(entry->node(), -1).append(delim, -1);\r
- line.replaceAll("!full!", 6, replacement.str(), replacement.length());\r
- }\r
- if (strstr(arguments, "!path!") != NULL){\r
- replacement.set(delim, -1).append(entry->m_path).append(delim, -1);\r
- line.replaceAll("!path!", 6, replacement.str(), replacement.length());\r
- }\r
- if (strstr(arguments, "!basename!") != NULL){\r
- replacement.set(delim, -1).append(entry->node(), -1).append(delim, -1);\r
- line.replaceAll("!basename!", 10, replacement.str(), replacement.length());\r
- }\r
- if (strstr(arguments, "!name!") != NULL){\r
- replacement.set(delim, -1).append(entry->node(), -1);\r
- int ix = replacement.rindexOf(".", 1);\r
- if (ix > 1)\r
- replacement.setLength(ix);\r
- replacement.append(delim, -1);\r
- line.replaceAll("!name!", 6, replacement.str(), replacement.length());\r
- }\r
- if (strstr(arguments, "!ext!") != NULL){\r
- replacement.set(delim, -1).append(entry->node(), -1);\r
- int ix = replacement.rindexOf(".", 1);\r
- if (ix > 1)\r
- replacement.remove(1, ix - 1);\r
- else\r
- replacement.setLength(1);\r
- replacement.append(delim, -1);\r
- line.replaceAll("!ext!", 5, replacement.str(), replacement.length());\r
- }\r
- // We remove the unwanted delimiters (see above):\r
- ReByteBuffer buffer;\r
- buffer.set(delim, -1).appendChar('\01').append(delim, -1);\r
- line.replaceAll(buffer.str(), buffer.length(), "", 0);\r
+ addStandardFilterOptions();\r
+}\r
+\r
+static void replaceMakros(const char* arguments, ReDirStatus_t* entry,\r
+ const char* delim, ReByteBuffer& line) {\r
+ line.set(arguments, -1);\r
+ // we prepare the removal of unwanted delimiters in constructed placeholders:\r
+ // example: !path!!name!: without correction: "e:\\data\\""xxx"\r
+ // We want: "e:\\data\\xxx"\r
+ line.replaceAll("!!", 2, "!\x01!", 3);\r
+ ReByteBuffer replacement;\r
+ if (strstr(arguments, "!full!") != NULL) {\r
+ replacement.set(delim, -1).append(entry->m_path);\r
+ replacement.append(entry->node(), -1).append(delim, -1);\r
+ line.replaceAll("!full!", 6, replacement.str(), replacement.length());\r
+ }\r
+ if (strstr(arguments, "!path!") != NULL) {\r
+ replacement.set(delim, -1).append(entry->m_path).append(delim, -1);\r
+ line.replaceAll("!path!", 6, replacement.str(), replacement.length());\r
+ }\r
+ if (strstr(arguments, "!basename!") != NULL) {\r
+ replacement.set(delim, -1).append(entry->node(), -1).append(delim, -1);\r
+ line.replaceAll("!basename!", 10, replacement.str(),\r
+ replacement.length());\r
+ }\r
+ if (strstr(arguments, "!name!") != NULL) {\r
+ replacement.set(delim, -1).append(entry->node(), -1);\r
+ int ix = replacement.rindexOf(".", 1);\r
+ if (ix > 1)\r
+ replacement.setLength(ix);\r
+ replacement.append(delim, -1);\r
+ line.replaceAll("!name!", 6, replacement.str(), replacement.length());\r
+ }\r
+ if (strstr(arguments, "!ext!") != NULL) {\r
+ replacement.set(delim, -1).append(entry->node(), -1);\r
+ int ix = replacement.rindexOf(".", 1);\r
+ if (ix > 1)\r
+ replacement.remove(1, ix - 1);\r
+ else\r
+ replacement.setLength(1);\r
+ replacement.append(delim, -1);\r
+ line.replaceAll("!ext!", 5, replacement.str(), replacement.length());\r
+ }\r
+ // We remove the unwanted delimiters (see above):\r
+ ReByteBuffer buffer;\r
+ buffer.set(delim, -1).appendChar('\01').append(delim, -1);\r
+ line.replaceAll(buffer.str(), buffer.length(), "", 0);\r
}\r
/**\r
* Creates the batch file.\r
*/\r
-void ReDirBatch::doIt(){\r
+void ReDirBatch::doIt() {\r
ReByteBuffer buffer;\r
m_programArgs.getString("arguments", m_arguments);\r
m_programArgs.getString("script", m_script);\r
if (m_arguments.length() + m_script.length() == 0)\r
- help(i18n("one of the option must be set: -a (--arguments) or -c (--script)"));\r
+ help(\r
+ i18n(\r
+ "one of the option must be set: -a (--arguments) or -c (--script)"));\r
#if defined __WIN32__\r
m_isExe = m_programArgs.getBool("isexe");\r
#endif\r
m_programArgs.getString("first", buffer);\r
- if (buffer.length() > 0)\r
- fprintf(m_output, "%s\n", buffer.str());\r
+ if (buffer.length() > 0)\r
+ fprintf(m_output, "%s\n", buffer.str());\r
processFileArguments();\r
#if defined __linux__\r
static const char* prefix = "# ";\r
#elif defined __WIN32__\r
static const char* prefix = "rem ";\r
#endif\r
- printSummary(prefix);\r
+ printSummary (prefix);\r
}\r
\r
/**\r
*\r
* @param entry the properties of the directory to process\r
*/\r
-void ReDirBatch::processDir(ReDirStatus_t* entry){\r
+void ReDirBatch::processDir(ReDirStatus_t* entry) {\r
processFile(entry);\r
}\r
\r
*\r
* @param entry the properties of the file to process\r
*/\r
-void ReDirBatch::processFile(ReDirStatus_t* entry){\r
+void ReDirBatch::processFile(ReDirStatus_t* entry) {\r
ReByteBuffer line;\r
#if defined __linux__\r
- static const char* delim = "'";\r
+ static const char* delim = "'";\r
#elif defined __WIN32__\r
static const char* delim = "\"";\r
#endif\r
- if (m_script.length() > 0){\r
+ if (m_script.length() > 0) {\r
#if defined __WIN32__\r
if (! m_isExe)\r
- line.append("call ");\r
+ line.append("call ");\r
#endif\r
line.append(m_script).appendChar(' ').appendChar(delim[0]);\r
line.append(entry->m_path).append(entry->node(), -1);\r
* @param logger logger for error handling\r
*/\r
ReDirList::ReDirList(ReLogger* logger) :\r
- ReTool(s_listUsage, s_listExamples, 0, 0, 0, true, logger),\r
- m_widthOwner(13),\r
- m_shortFormat(false),\r
- m_withRights(false),\r
- m_numerical(false)\r
-{\r
+ ReTool(s_listUsage, s_listExamples, 0, 0, 0, true, logger),\r
+ m_widthOwner(13),\r
+ m_shortFormat(false),\r
+ m_withRights(false),\r
+ m_numerical(false) {\r
// standard short options: D d O o P p T t v y Z z\r
- m_programArgs.addBool("short", i18n("output is only path and basename"),\r
- '1', "--short", false);\r
- m_programArgs.addBool("rights", i18n("show the permission/right info"),\r
- 'r', "--rights", false);\r
- m_programArgs.addBool("numerical", i18n("the permission/right info is shown as numbers"),\r
- 'n', "--numerical", false);\r
- m_programArgs.addInt("owner", i18n("space reserved for owner/group"), \r
- 'w', "--width-owner", 13);\r
- addStandardFilterOptions();\r
+ m_programArgs.addBool("short", i18n("output is only path and basename"),\r
+ '1', "--short", false);\r
+ m_programArgs.addBool("rights", i18n("show the permission/right info"), 'r',\r
+ "--rights", false);\r
+ m_programArgs.addBool("numerical",\r
+ i18n("the permission/right info is shown as numbers"), 'n',\r
+ "--numerical", false);\r
+ m_programArgs.addInt("owner", i18n("space reserved for owner/group"), 'w',\r
+ "--width-owner", 13);\r
+ addStandardFilterOptions();\r
}\r
\r
/**\r
* Lists the metadata of the specified files.\r
*/\r
-void ReDirList::doIt(){\r
+void ReDirList::doIt() {\r
m_shortFormat = m_programArgs.getBool("short");\r
m_withRights = m_programArgs.getBool("rights");\r
m_numerical = m_programArgs.getBool("numerical");\r
*\r
* @param entry the properties of the directory to process\r
*/\r
-void ReDirList::processDir(ReDirStatus_t* entry){\r
+void ReDirList::processDir(ReDirStatus_t* entry) {\r
processFile(entry);\r
}\r
/**\r
*\r
* @param entry the properties of the file to process\r
*/\r
-void ReDirList::processFile(ReDirStatus_t* entry){\r
+void ReDirList::processFile(ReDirStatus_t* entry) {\r
ReByteBuffer bufferRights;\r
ReByteBuffer bufferTime;\r
if (m_shortFormat)\r
else {\r
if (m_withRights)\r
entry->rightsAsString(bufferRights, m_numerical, m_widthOwner);\r
- fprintf(m_output, "%c%s %12.6f %s %s%s\n",\r
- entry->typeAsChar(),\r
- bufferRights.str(),\r
- entry->fileSize() / 1E6,\r
- entry->filetimeAsString(bufferTime),\r
- entry->m_path.str(), entry->node());\r
+ fprintf(m_output, "%c%s %12.6f %s %s%s\n", entry->typeAsChar(),\r
+ bufferRights.str(), entry->fileSize() / 1E6,\r
+ entry->filetimeAsString(bufferTime), entry->m_path.str(),\r
+ entry->node());\r
}\r
}\r
\r
* @param logger logger for error handling\r
*/\r
ReDirMD5::ReDirMD5(ReLogger* logger) :\r
- ReTool(s_md5Usage, s_md5Examples, 0, 0, 0, true, logger),\r
- m_buffer()\r
-{\r
+ ReTool(s_md5Usage, s_md5Examples, 0, 0, 0, true, logger),\r
+ m_buffer() {\r
// standard short options: D d O o P p T t v y Z z\r
- m_programArgs.addInt("buffersize", i18n("buffer size for file reading (in KiByte)"), \r
- 'b', "--buffer-size", 4*1024);\r
- addStandardFilterOptions();\r
+ m_programArgs.addInt("buffersize",\r
+ i18n("buffer size for file reading (in KiByte)"), 'b', "--buffer-size",\r
+ 4 * 1024);\r
+ addStandardFilterOptions();\r
}\r
\r
/**\r
* Lists the metadata of the specified files.\r
*/\r
-void ReDirMD5::doIt(){\r
+void ReDirMD5::doIt() {\r
int size = m_programArgs.getInt("buffersize") * 1024;\r
m_buffer.setLength(size);\r
processFileArguments();\r
*\r
* @param entry the properties of the directory to process\r
*/\r
-void ReDirMD5::processDir(ReDirStatus_t* entry){\r
+void ReDirMD5::processDir(ReDirStatus_t* entry) {\r
}\r
/**\r
* Processes one file.\r
*\r
* @param entry the properties of the file to process\r
*/\r
-void ReDirMD5::processFile(ReDirStatus_t* entry){\r
+void ReDirMD5::processFile(ReDirStatus_t* entry) {\r
const char* name = entry->fullName();\r
FILE* fp = fopen(name, "rb");\r
if (fp != NULL) {\r
uint8_t* buffer = reinterpret_cast<uint8_t*>(m_buffer.buffer());\r
size_t blockSize = m_buffer.length();\r
\r
- while( (readBytes = fread(buffer, 1, blockSize, fp)) > 0){\r
+ while ((readBytes = fread(buffer, 1, blockSize, fp)) > 0) {\r
digest.update(buffer, readBytes);\r
}\r
fclose(fp);\r
}\r
}\r
\r
-\r
/**\r
* Calculates the statistic of a directory tree.\r
*\r
*\r
*/\r
const ReStringList& ReDirStatistic::calculate(const char* base, int level,\r
- void (*formatter)(const ReDirStatisticData& data, ReDirStatistic& parent,\r
- ReByteBuffer& line)){\r
+ void (*formatter)(const ReDirStatisticData& data, ReDirStatistic& parent,\r
+ ReByteBuffer& line)) {\r
ReDirEntryFilter_t filter;\r
ReTraverser traverser(base, this);\r
setFilterFromProgramArgs(filter);\r
level = 1024;\r
else if (level < 0)\r
level = 0;\r
- m_list.clear();\r
+ m_list.clear();\r
ReDirStatisticData** dataStack = new ReDirStatisticData*[level + 1];\r
memset(dataStack, 0, sizeof dataStack[0] * (level + 1));\r
dataStack[0] = new ReDirStatisticData();\r
current->m_path.set(base, -1);\r
ReByteBuffer line;\r
bool useFilter = filter.m_minSize > 0 || filter.m_maxSize != -1\r
- || ! filetimeIsUndefined(filter.m_minAge) || ! filetimeIsUndefined(filter.m_maxAge)\r
- || m_nodePatterns.count() > 0;\r
- while( (entry = traverser.rawNextFile(currentDepth))){\r
- if (currentDepth <= level && ! entry->m_path.equals(current->m_path)){\r
- if (currentDepth <= topOfStack){\r
+ || !filetimeIsUndefined(filter.m_minAge)\r
+ || !filetimeIsUndefined(filter.m_maxAge) || m_nodePatterns.count() > 0;\r
+ while ((entry = traverser.rawNextFile(currentDepth))) {\r
+ if (currentDepth <= level && !entry->m_path.equals(current->m_path)) {\r
+ if (currentDepth <= topOfStack) {\r
// close the entries of the stack above the new top level:\r
- while(topOfStack >= currentDepth){\r
+ while (topOfStack >= currentDepth) {\r
// Add the data to the parent:\r
- if (topOfStack > 0)\r
- dataStack[topOfStack - 1]->add(*dataStack[topOfStack]);\r
- // Append it to the result:\r
+ if (topOfStack > 0)\r
+ dataStack[topOfStack - 1]->add(*dataStack[topOfStack]);\r
+ // Append it to the result:\r
(*formatter)(*dataStack[topOfStack], *this, line);\r
m_list.append(line);\r
- topOfStack--;\r
+ topOfStack--;\r
}\r
- // We reuse the top of stack:\r
- topOfStack++;\r
- current = dataStack[topOfStack];\r
- // exchange the top of stack with the new found directory:\r
- current->clear();\r
- current->m_path.set(entry->m_path.str(), entry->m_path.length());;\r
+ // We reuse the top of stack:\r
+ topOfStack++;\r
+ current = dataStack[topOfStack];\r
+ // exchange the top of stack with the new found directory:\r
+ current->clear();\r
+ current->m_path.set(entry->m_path.str(),\r
+ entry->m_path.length());\r
+ ;\r
} else {\r
// set up a new stack entry:\r
if (currentDepth != topOfStack + 1)\r
else\r
dataStack[topOfStack]->clear();\r
current = dataStack[topOfStack];\r
- current->m_path.set(entry->m_path.str(), entry->m_path.length());\r
+ current->m_path.set(entry->m_path.str(),\r
+ entry->m_path.length());\r
}\r
}\r
- if (entry->isDirectory()){\r
+ if (entry->isDirectory()) {\r
current->m_directories++;\r
- } else if (! useFilter || filter.match(*entry)){\r
+ } else if (!useFilter || filter.match(*entry)) {\r
current->m_sizes += entry->fileSize();\r
current->m_files++;\r
}\r
}\r
- // close all dirs with parents:\r
- while(topOfStack > 0){\r
+ // close all dirs with parents:\r
+ while (topOfStack > 0) {\r
// Add the data to the parent:\r
dataStack[topOfStack - 1]->add(*dataStack[topOfStack]);\r
// Append it to the result:\r
(*formatter)(*dataStack[topOfStack], *this, line);\r
m_list.append(line);\r
- topOfStack--;\r
+ topOfStack--;\r
}\r
- // ... and the overall summery:\r
- (*formatter)(*dataStack[0], *this, line);\r
+ // ... and the overall summery:\r
+ (*formatter)(*dataStack[0], *this, line);\r
m_list.append(line);\r
// free the resources:\r
for (int ix = 0; ix <= level; ix++)\r
* @param arc count of arguments in <code>argv</code>\r
* @param argv the program arguments.\r
*/\r
-void ReDirStatistic::doIt(){\r
+void ReDirStatistic::doIt() {\r
int depth = 1;\r
- if (m_programArgs.getArgCount() > 1){\r
+ if (m_programArgs.getArgCount() > 1) {\r
const char* arg1 = m_programArgs.getArg(1);\r
if (ReStringUtils::lengthOfUnsigned(arg1, -1, (unsigned *) &depth) == 0)\r
m_programArgs.help("depth is not an integer", false, stdout);\r
}\r
- void (*proc) (const ReDirStatisticData& data,\r
- ReDirStatistic& parent, ReByteBuffer& line) = &formatWithSizeFilesAndDirs;\r
+ void (*proc)(const ReDirStatisticData& data, ReDirStatistic& parent,\r
+ ReByteBuffer& line) = &formatWithSizeFilesAndDirs;\r
if (m_programArgs.getBool("kbyte"))\r
proc = &formatLikeDu;\r
const ReStringList& list = calculate(m_programArgs.getArg(0), depth, proc);\r
ReByteBuffer buffer;\r
- for (size_t ix = 0; ix < list.count(); ix++){\r
+ for (size_t ix = 0; ix < list.count(); ix++) {\r
buffer.set(list.strOf(ix), list.strLengthOf(ix));\r
fprintf(m_output, "%s\n", buffer.str());\r
}\r
- if (m_verboseLevel >= V_SUMMARY){\r
+ if (m_verboseLevel >= V_SUMMARY) {\r
int duration = int(time(NULL) - m_start);\r
fprintf(m_output, "=== duration: ");\r
if (duration >= 3600)\r
* <code>ReDirStatistic</code>)\r
* @param line OUT: the formatted line, the conclusion of the statistic data\r
*/\r
-void formatLikeDu(const ReDirStatisticData& data,\r
- ReDirStatistic& parent, ReByteBuffer& line){\r
+void formatLikeDu(const ReDirStatisticData& data, ReDirStatistic& parent,\r
+ ReByteBuffer& line) {\r
line.setLength(0);\r
- // Round up to the next KiByte:\r
- line.appendInt(int((data.m_sizes + 1023) / 1024)).append("\t").append(data.m_path);\r
+ // Round up to the next KiByte:\r
+ line.appendInt(int((data.m_sizes + 1023) / 1024)).append("\t").append(\r
+ data.m_path);\r
}\r
\r
/**\r
* @param line OUT: the formatted line, the conclusion of the statistic data\r
*/\r
void formatWithSizeFilesAndDirs(const ReDirStatisticData& data,\r
- ReDirStatistic& parent, ReByteBuffer& line){\r
+ ReDirStatistic& parent, ReByteBuffer& line) {\r
line.setLength(0);\r
- // Round up to the next KiByte:\r
- char buffer[256];\r
- _snprintf(buffer, sizeof buffer, "%14.6f MB %7d %7d\t",\r
- data.m_sizes / 1E6, data.m_files, data.m_directories);\r
+ // Round up to the next KiByte:\r
+ char buffer[256];\r
+ _snprintf(buffer, sizeof buffer, "%14.6f MB %7d %7d\t", data.m_sizes / 1E6,\r
+ data.m_files, data.m_directories);\r
line.append(buffer, -1).append(data.m_path);\r
}\r
/**\r
* @param logger logger for error handling\r
*/\r
ReDirTouch::ReDirTouch(ReLogger* logger) :\r
- ReTool(s_touchUsage, s_touchExamples, 1, 0, 0, false, logger),\r
- m_buffer()\r
- //m_modified()\r
- //m_accessed()\r
+ ReTool(s_touchUsage, s_touchExamples, 1, 0, 0, false, logger),\r
+ m_buffer()\r
+//m_modified()\r
+//m_accessed()\r
{\r
setFiletimeUndef(m_modified);\r
setFiletimeUndef(m_accessed);\r
// standard short options: D d O o P p T t v y Z z\r
- m_programArgs.addString("accessed",\r
- i18n("the new access time.\n"\r
- "Formats: absolute, relative to now, relative to the current filetime\n"\r
- "[yyyy.mm.dd/]HH:MM:SS \n"\r
- "now-<count>{s|m|h|d}\n"\r
- "{+|-}<count>{s|m|h|d}"),\r
- 'a', "--accessed", false, NULL);\r
- m_programArgs.addString("modified",\r
- i18n("the new modification time.\n"\r
- "Formats: absolute, relative to now, relative to the current filetime\n"\r
- "[yyyy.mm.dd/]HH:MM:SS\n"\r
- "now-<count>{s|m|h|d}\n"\r
- "{+|-}<count>{s|m|h|d}"),\r
- 'm', "--modified", false, NULL);\r
- addStandardFilterOptions();\r
+ m_programArgs.addString("accessed", i18n("the new access time.\n"\r
+ "Formats: absolute, relative to now, relative to the current filetime\n"\r
+ "[yyyy.mm.dd/]HH:MM:SS \n"\r
+ "now-<count>{s|m|h|d}\n"\r
+ "{+|-}<count>{s|m|h|d}"), 'a', "--accessed", false, NULL);\r
+ m_programArgs.addString("modified", i18n("the new modification time.\n"\r
+ "Formats: absolute, relative to now, relative to the current filetime\n"\r
+ "[yyyy.mm.dd/]HH:MM:SS\n"\r
+ "now-<count>{s|m|h|d}\n"\r
+ "{+|-}<count>{s|m|h|d}"), 'm', "--modified", false, NULL);\r
+ addStandardFilterOptions();\r
}\r
/**\r
* Sets the filetime for the specified files.\r
*/\r
-void ReDirTouch::doIt(){\r
+void ReDirTouch::doIt() {\r
ReByteBuffer buffer;\r
if (m_programArgs.getString("modified", buffer)[0] != '\0')\r
m_modified = checkDate(buffer.str());\r
*\r
* @param entry the properties of the directory to process\r
*/\r
-void ReDirTouch::processDir(ReDirStatus_t* entry){\r
+void ReDirTouch::processDir(ReDirStatus_t* entry) {\r
processFile(entry);\r
}\r
\r
-static bool isAbsoluteTime(ReFileTime_t& time){\r
+static bool isAbsoluteTime(ReFileTime_t& time) {\r
#if defined __linux__\r
- static struct tm year1980 = { 0, 0, 0, 1, 1 - 1, 1980-1900 };\r
+ static struct tm year1980 = {0, 0, 0, 1, 1 - 1, 1980-1900};\r
static time_t time1980 = mktime(&year1980);\r
return time.tv_sec >= time1980;\r
#elif defined __WIN32__\r
- static ReFileTime_t filetime1980 = { 2148603904, 27846551 };\r
+ static ReFileTime_t filetime1980 = {2148603904, 27846551};\r
bool rc = time > filetime1980;\r
return rc;\r
#endif\r
}\r
-static void addRelativeTime(ReFileTime_t& absTime, const ReFileTime_t& relTime){\r
+static void addRelativeTime(ReFileTime_t& absTime,\r
+ const ReFileTime_t& relTime) {\r
#if defined __linux__\r
- if ( (absTime.tv_nsec += relTime.tv_nsec) >= 1000*1000*1000){\r
+ if ( (absTime.tv_nsec += relTime.tv_nsec) >= 1000*1000*1000) {\r
absTime.tv_nsec -= 1000*1000*1000;\r
absTime.tv_sec += 1;\r
}\r
uint64_t absValue = ((uint64_t) absTime.dwHighDateTime << 32) | absTime.dwLowDateTime;\r
uint64_t relValue = ((uint64_t) relTime.dwHighDateTime << 32) | relTime.dwLowDateTime;\r
absValue += relValue;\r
- absTime.dwHighDateTime = (uint32_t) (absValue >> 32); \r
- absTime.dwLowDateTime = (uint32_t) absValue; \r
+ absTime.dwHighDateTime = (uint32_t) (absValue >> 32);\r
+ absTime.dwLowDateTime = (uint32_t) absValue;\r
#endif\r
}\r
/**\r
*\r
* @param entry the properties of the file to process\r
*/\r
-void ReDirTouch::processFile(ReDirStatus_t* entry){\r
+void ReDirTouch::processFile(ReDirStatus_t* entry) {\r
ReFileTime_t modified = *entry->modified();\r
int countTimes = 0;\r
- if (! filetimeIsUndefined(m_modified)){\r
+ if (!filetimeIsUndefined(m_modified)) {\r
countTimes++;\r
if (isAbsoluteTime(m_modified))\r
modified = m_modified;\r
addRelativeTime(modified, m_modified);\r
}\r
ReFileTime_t accessed = *entry->accessed();\r
- if (! filetimeIsUndefined(m_accessed)){\r
+ if (!filetimeIsUndefined(m_accessed)) {\r
countTimes++;\r
if (isAbsoluteTime(m_accessed))\r
accessed = m_accessed;\r
}\r
const char* name = entry->fullName();\r
if (touch(name, modified, accessed, ReLogger::globalLogger()) == 0\r
- && m_verboseLevel >= V_NORMAL){\r
+ && m_verboseLevel >= V_NORMAL) {\r
ReByteBuffer bufferTime;\r
ReByteBuffer bufferTime2;\r
- if (m_verboseLevel == V_NORMAL){\r
+ if (m_verboseLevel == V_NORMAL) {\r
if (countTimes == 2)\r
fprintf(m_output, "%s | %s | %s\n",\r
- ReDirStatus_t::filetimeToString(&modified, bufferTime),\r
- ReDirStatus_t::filetimeToString(&accessed, bufferTime2),\r
- name);\r
+ ReDirStatus_t::filetimeToString(&modified, bufferTime),\r
+ ReDirStatus_t::filetimeToString(&accessed, bufferTime2),\r
+ name);\r
else {\r
ReDirStatus_t::filetimeToString(\r
- filetimeIsUndefined(m_modified) ? &accessed : &modified,\r
- bufferTime);\r
+ filetimeIsUndefined(m_modified) ? &accessed : &modified,\r
+ bufferTime);\r
fprintf(m_output, "%s %s\n", bufferTime.str(), name);\r
}\r
} else {\r
ReByteBuffer bufferTime4;\r
if (countTimes == 2)\r
fprintf(m_output, "%s -> %s | %s -> %s | %s\n",\r
- ReDirStatus_t::filetimeToString(entry->modified(), bufferTime),\r
- ReDirStatus_t::filetimeToString(&modified, bufferTime2),\r
- ReDirStatus_t::filetimeToString(entry->accessed(), bufferTime3),\r
- ReDirStatus_t::filetimeToString(&accessed, bufferTime4),\r
- name);\r
+ ReDirStatus_t::filetimeToString(entry->modified(),\r
+ bufferTime),\r
+ ReDirStatus_t::filetimeToString(&modified, bufferTime2),\r
+ ReDirStatus_t::filetimeToString(entry->accessed(),\r
+ bufferTime3),\r
+ ReDirStatus_t::filetimeToString(&accessed, bufferTime4),\r
+ name);\r
else {\r
ReDirStatus_t::filetimeToString(\r
- filetimeIsUndefined(m_modified) ? &m_accessed : &m_modified,\r
- bufferTime);\r
+ filetimeIsUndefined(m_modified) ? &m_accessed : &m_modified,\r
+ bufferTime);\r
fprintf(m_output, "%s -> %s %s\n", bufferTime.str(), name);\r
}\r
}\r
* @param logger NULL or the logger\r
*/\r
ReErrNo_t ReDirTouch::touch(const char* filename, const ReFileTime_t& modified,\r
- const ReFileTime_t& accessed, ReLogger* logger){\r
+ const ReFileTime_t& accessed, ReLogger* logger) {\r
#if defined __linux__\r
timeval times[2];\r
times[0].tv_sec = accessed.tv_sec;\r
FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING,\r
FILE_ATTRIBUTE_NORMAL, NULL);\r
if (handle == INVALID_HANDLE_VALUE)\r
- rc = GetLastError();\r
+ rc = GetLastError();\r
else {\r
if (! SetFileTime(handle, (LPFILETIME) NULL, &accessed, &modified))\r
- rc = GetLastError();\r
+ rc = GetLastError();\r
CloseHandle(handle);\r
}\r
#endif\r
if (rc != 0 && logger != NULL)\r
logger->sayF(LOG_ERROR | CAT_FILE, LC_TOUCH_1,\r
- i18n("cannot change filetime: $1 (errno: $2)")).arg(filename)\r
- .arg(errno).end();\r
+ i18n("cannot change filetime: $1 (errno: $2)")).arg(filename).arg(\r
+ errno).end();\r
return rc;\r
}\r
\r
-\r
-\r
/**\r
* Prints a vector of lines.\r
* \r
* @param lines a vector of lines without newline ('\n')\r
*/\r
-static void printField(const char** lines){\r
- for (int ix = 0; lines[ix] != NULL; ix++){\r
- printf("%s\n", lines[ix]);\r
- }\r
+static void printField(const char** lines) {\r
+ for (int ix = 0; lines[ix] != NULL; ix++) {\r
+ printf("%s\n", lines[ix]);\r
+ }\r
}\r
\r
/**\r
* Prints a message how to use the module and exits.\r
*/\r
-void ReDirTools::usage(ReTool& tool){\r
- tool.programArgs().help(NULL, false, stdout);\r
+void ReDirTools::usage(ReTool& tool) {\r
+ tool.programArgs().help(NULL, false, stdout);\r
}\r
\r
/**\r
* @param msg an error message\r
* @param msg2 an addition to the error message or NULL\r
*/\r
-void ReDirTools::usage(const char* msg, const char* msg2){\r
- printf ("Version: %s\n", m_version);\r
- printf ("usage: dirtool <command> <opt>\n"\r
+void ReDirTools::usage(const char* msg, const char* msg2) {\r
+ printf("Version: %s\n", m_version);\r
+ printf("usage: dirtool <command> <opt>\n"\r
"call 'dirtool help' for more info\n");\r
- if (msg != NULL)\r
- printf ("+++ %s%s\n", msg, msg2 == NULL ? "" : msg2);\r
- exit(1);\r
+ if (msg != NULL)\r
+ printf("+++ %s%s\n", msg, msg2 == NULL ? "" : msg2);\r
+ exit(1);\r
}\r
\r
/**\r
* @param path the name of the subdir to create\r
*/\r
void ReDirSync::makeDirWithParents(ReByteBuffer& path, int minWidth,\r
- ReTraverser& traverser){\r
- if (! exists(path)){\r
+ ReTraverser& traverser) {\r
+ if (!exists(path)) {\r
ReFileProperties_t* props = NULL;\r
#if defined __linux__\r
ReDirStatus_t* entry = traverser.topOfStack();\r
* @param logger logger for error handling\r
*/\r
ReDirSync::ReDirSync(ReLogger* logger) :\r
- ReTool(s_syncUsage, s_syncExamples, 2, 0, 1, false, logger),\r
- m_buffer()\r
-{\r
+ ReTool(s_syncUsage, s_syncExamples, 2, 0, 1, false, logger),\r
+ m_buffer() {\r
// standard short options: D d O o P p T t v y Z z\r
- m_buffer.ensureSize(4u*1024u*1024u);\r
- m_programArgs.addBool("add",\r
- i18n("copies only files which does not exist on the target"),\r
- 'a', "add", false);\r
- m_programArgs.addBool("dry",\r
- i18n("does nothing, but says what should be done"),\r
- 'Y', "dry", false);\r
- m_programArgs.addInt("timediff",\r
- i18n("filetime difference is considered to be equal\n"\r
- "if the difference is less than this value (in seconds)"),\r
- 'I', "time-delta", 2);\r
- m_programArgs.addBool("ignoredate",\r
- i18n("the modification is recognized only by the different size (not time)"),\r
- 'i', "ignore-time", false);\r
- m_programArgs.addBool("mustexist",\r
- i18n("files which don't exist on the target will not be copied"),\r
- 'm', "must-exist", false);\r
- addStandardFilterOptions();\r
+ m_buffer.ensureSize(4u * 1024u * 1024u);\r
+ m_programArgs.addBool("add",\r
+ i18n("copies only files which does not exist on the target"), 'a',\r
+ "add", false);\r
+ m_programArgs.addBool("dry",\r
+ i18n("does nothing, but says what should be done"), 'Y', "dry", false);\r
+ m_programArgs.addInt("timediff",\r
+ i18n("filetime difference is considered to be equal\n"\r
+ "if the difference is less than this value (in seconds)"), 'I',\r
+ "time-delta", 2);\r
+ m_programArgs.addBool("ignoredate",\r
+ i18n(\r
+ "the modification is recognized only by the different size (not time)"),\r
+ 'i', "ignore-time", false);\r
+ m_programArgs.addBool("mustexist",\r
+ i18n("files which don't exist on the target will not be copied"), 'm',\r
+ "must-exist", false);\r
+ addStandardFilterOptions();\r
}\r
\r
/**\r
* @param entry the source file info\r
* @param target the name of the target file\r
*/\r
-void ReDirSync::copyFile(ReDirStatus_t* entry, const char* target){\r
+void ReDirSync::copyFile(ReDirStatus_t* entry, const char* target) {\r
ReFileProperties_t* props;\r
#ifdef __linux__\r
props = &entry->m_status;\r
props = &properties;\r
#endif\r
copyFile(entry->fullName(), props, target, m_buffer,\r
- ReLogger::globalLogger());\r
+ ReLogger::globalLogger());\r
}\r
\r
/**\r
* <code>false</code>error occurred\r
*/\r
bool ReDirSync::copyFile(const char* source, ReFileProperties_t* properties,\r
- const char* target, ReByteBuffer& buffer, ReLogger* logger){\r
+ const char* target, ReByteBuffer& buffer, ReLogger* logger) {\r
bool rc = false;\r
#ifdef __linux__\r
struct stat info;\r
- if (properties == NULL){\r
+ if (properties == NULL) {\r
if (stat(source, &info) == 0)\r
- properties = &info;\r
+ properties = &info;\r
else {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_1,\r
- i18n("could not find: $1 (errno: $2)")).arg(source)\r
- .arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_1,\r
+ i18n("could not find: $1 (errno: $2)")).arg(source)\r
+ .arg(errno).end();\r
}\r
}\r
FILE* fpSource = fopen(source, "rb");\r
- if (fpSource == NULL){\r
+ if (fpSource == NULL) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_2,\r
- i18n("cannot open $1 (errno: $2)"))\r
- .arg(source).arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_2,\r
+ i18n("cannot open $1 (errno: $2)"))\r
+ .arg(source).arg(errno).end();\r
} else {\r
ReFileSize_t size = properties == NULL ? 0x7fffffff : properties->st_size;\r
FILE* fpTarget = fopen(target, "w");\r
- if (fpTarget == NULL){\r
+ if (fpTarget == NULL) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_3,\r
- i18n("cannot open $1 (errno: $2)"))\r
- .arg(target).arg(errno).end();\r
- } else{\r
- while(size > 0){\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_3,\r
+ i18n("cannot open $1 (errno: $2)"))\r
+ .arg(target).arg(errno).end();\r
+ } else {\r
+ while(size > 0) {\r
size_t blockSize = buffer.capacity();\r
if ((int) blockSize > size)\r
- blockSize = size;\r
- if (fread(buffer.buffer(), blockSize, 1, fpSource) != 1){\r
+ blockSize = size;\r
+ if (fread(buffer.buffer(), blockSize, 1, fpSource) != 1) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_5,\r
- i18n("cannot read $1 (errno: $2)"))\r
- .arg(source).arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_5,\r
+ i18n("cannot read $1 (errno: $2)"))\r
+ .arg(source).arg(errno).end();\r
break;\r
}\r
size_t written;\r
if ((written = fwrite(buffer.buffer(), 1, blockSize,\r
- fpTarget)) != blockSize){\r
+ fpTarget)) != blockSize) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_6,\r
- i18n("cannot write $1 [$2] (errno: $3)"))\r
- .arg(target).arg(written).arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_COPY_FILE_6,\r
+ i18n("cannot write $1 [$2] (errno: $3)"))\r
+ .arg(target).arg(written).arg(errno).end();\r
break;\r
}\r
size -= blockSize;\r
rc = size == 0ll;\r
fclose(fpTarget);\r
if (properties != NULL)\r
- setProperties(target, properties, logger);\r
+ setProperties(target, properties, logger);\r
}\r
fclose(fpSource);\r
}\r
#elif defined __WIN32__\r
- BOOL cancel = false;\r
- rc = CopyFileExA(source, target, NULL, NULL, &cancel, COPY_FILE_NO_BUFFERING) != 0;\r
- int errNo = 0;\r
- if (! rc)\r
- errNo = GetLastError();\r
+ BOOL cancel = false;\r
+ rc = CopyFileExA(source, target, NULL, NULL, &cancel, COPY_FILE_NO_BUFFERING) != 0;\r
+ int errNo = 0;\r
+ if (! rc)\r
+ errNo = GetLastError();\r
#endif\r
return rc;\r
}\r
* <code>false</code>: error occurred\r
*/\r
bool ReDirSync::setProperties(const char* fullName,\r
- ReFileProperties_t* properties, ReLogger* logger){\r
+ ReFileProperties_t* properties, ReLogger* logger) {\r
bool rc = true;\r
#if defined __linux__\r
timeval times[2];\r
times[0].tv_usec = properties->st_atim.tv_nsec / 1000;\r
times[1].tv_sec = properties->st_mtim.tv_sec;\r
times[1].tv_usec = properties->st_mtim.tv_nsec / 1000;\r
- if (utimes(fullName, times) != 0){\r
+ if (utimes(fullName, times) != 0) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_1,\r
- i18n("cannot change file times: $1 (errno: $2)"))\r
- .arg(fullName).arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_1,\r
+ i18n("cannot change file times: $1 (errno: $2)"))\r
+ .arg(fullName).arg(errno).end();\r
rc = false;\r
}\r
int rights = properties->st_mode & (S_IRWXO | S_IRWXG | S_IRWXU);\r
if (chmod(fullName, rights) != 0) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_2,\r
- i18n("cannot change file modes: $1 (errno: $2)"))\r
- .arg(fullName).arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_2,\r
+ i18n("cannot change file modes: $1 (errno: $2)"))\r
+ .arg(fullName).arg(errno).end();\r
rc = false;\r
}\r
- if (chown(fullName, properties->st_uid, properties->st_gid) != 0){\r
+ if (chown(fullName, properties->st_uid, properties->st_gid) != 0) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_3,\r
- i18n("cannot change file owner: $1 (errno: $2)"))\r
- .arg(fullName).arg(errno).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_SET_PROPERTIES_3,\r
+ i18n("cannot change file owner: $1 (errno: $2)"))\r
+ .arg(fullName).arg(errno).end();\r
rc = false;\r
}\r
#endif\r
* <code>false</code>error occurred\r
*/\r
bool ReDirSync::makeDirectory(const char* directory, int minLength,\r
- ReFileProperties_t* properties, ReLogger* logger){\r
+ ReFileProperties_t* properties, ReLogger* logger) {\r
bool rc = true;\r
ReByteBuffer path(directory);\r
int start = 0;\r
int ixSlash = start < 0 ? 0 : start;\r
struct stat info;\r
// for all parents and the full path itself:\r
- while(ixSlash >= 0){\r
+ while (ixSlash >= 0) {\r
ixSlash = path.indexOf(OS_SEPARATOR_CHAR, ixSlash + 1);\r
// is the slash in front of the first node, e.g. 'e:\'?\r
if (ixSlash == start + 1)\r
// not a real node: take the next node\r
ixSlash = path.indexOf(OS_SEPARATOR_CHAR, ixSlash + 1);\r
- if (ixSlash >= 0){\r
+ if (ixSlash >= 0) {\r
// we handle only the next node:\r
path.buffer()[ixSlash] = '\0';\r
}\r
// does the node exist?\r
- if (lstat(path.str(), &info) != 0){\r
+ if (lstat(path.str(), &info) != 0) {\r
// no, then we make it:\r
- if (_mkdir(path.str(), ALLPERMS) != 0){\r
+ if (_mkdir(path.str(), ALLPERMS) != 0) {\r
if (logger != NULL)\r
logger->sayF(LOG_ERROR | CAT_FILE, LC_MAKE_DIR_1,\r
- i18n("could not make directory $1 (errno: $2)"))\r
- .arg(path.str()).arg(errno).end();\r
+ i18n("could not make directory $1 (errno: $2)")).arg(\r
+ path.str()).arg(errno).end();\r
rc = false;\r
break;\r
} else {\r
#endif\r
}\r
}\r
- if (ixSlash >= 0){\r
+ if (ixSlash >= 0) {\r
// restore the full path:\r
path.buffer()[ixSlash] = OS_SEPARATOR_CHAR;\r
}\r
/**\r
* Synchronizes two directory trees.\r
*/\r
-void ReDirSync::doIt(){\r
- ReDirEntryFilter_t filter;\r
- const char* sep = OS_SEPARATOR;\r
+void ReDirSync::doIt() {\r
+ ReDirEntryFilter_t filter;\r
+ const char* sep = OS_SEPARATOR;\r
ReByteBuffer buffer;\r
ReByteBuffer target(m_programArgs.getArg(m_programArgs.getArgCount() - 1));\r
target.removeLastChar(OS_SEPARATOR_CHAR);\r
- if (! exists(target))\r
+ if (!exists(target))\r
help(i18n("target does not exist: $1"), target.str());\r
- else if (! S_ISDIR(m_statInfo.st_mode))\r
+ else if (!S_ISDIR(m_statInfo.st_mode))\r
help(i18n("target is not a directory: $1"), target.str());\r
size_t lengthTargetBase = target.length();\r
bool addOnly = m_programArgs.getBool("add");\r
int treeDirs = 0;\r
int64_t treeSumSizes = 0ll;\r
ReByteBuffer source, targetFile;\r
- for (int ix = 0; ix < m_programArgs.getArgCount() - 1; ix++){\r
+ for (int ix = 0; ix < m_programArgs.getArgCount() - 1; ix++) {\r
source.set(m_programArgs.getArg(ix), -1);\r
target.setLength(lengthTargetBase);\r
bool endsWithSlash = source.endsWith(sep, 1);\r
if (endsWithSlash)\r
source.reduceLength();\r
- if (! exists(source))\r
+ if (!exists(source))\r
help(i18n("source does not exist: $1"), source.str());\r
- else if (! S_ISDIR(m_statInfo.st_mode))\r
+ else if (!S_ISDIR(m_statInfo.st_mode))\r
help(i18n("source is not a directory: $1"), source.str());\r
- if (! endsWithSlash){\r
+ if (!endsWithSlash) {\r
// the basename of the source will be appended to the target:\r
int startNode = source.rindexOf(sep, 1, 0, source.length() - 1);\r
target.appendChar(OS_SEPARATOR_CHAR);\r
int level;\r
ReDirStatus_t* entry;\r
ReByteBuffer line;\r
- while( (entry = m_traverser.nextFile(level, &filter)) != NULL){\r
+ while ((entry = m_traverser.nextFile(level, &filter)) != NULL) {\r
if (entry->isDirectory())\r
continue;\r
// append the new relative path from source to target:\r
target.setLength(ixTargetRelative);\r
target.append(entry->m_path.str() + ixSourceRelative, -1);\r
- if (! exists(target))\r
+ if (!exists(target))\r
makeDirWithParents(target, ixTargetRelative, m_traverser);\r
targetFile.set(target).append(entry->node(), -1);\r
- const char* targetRelativePath = targetFile.str() + ixTargetRelative + 1;\r
+ const char* targetRelativePath = targetFile.str() + ixTargetRelative\r
+ + 1;\r
bool targetExists = exists(targetFile);\r
- if (! targetExists && mustExist){\r
+ if (!targetExists && mustExist) {\r
if (m_verboseLevel == V_CHATTER)\r
- fprintf(m_output, "-ignored: %s does not exist\n", targetRelativePath);\r
+ fprintf(m_output, "-ignored: %s does not exist\n",\r
+ targetRelativePath);\r
continue;\r
}\r
- if (targetExists){\r
- if (addOnly){\r
+ if (targetExists) {\r
+ if (addOnly) {\r
if (m_verboseLevel >= V_CHATTER)\r
- fprintf(m_output, "~ignored: %s exists\n", targetRelativePath);\r
+ fprintf(m_output, "~ignored: %s exists\n",\r
+ targetRelativePath);\r
continue;\r
}\r
- if (ignoreDate && entry->fileSize() == m_statInfo.st_size){\r
+ if (ignoreDate && entry->fileSize() == m_statInfo.st_size) {\r
if (m_verboseLevel >= V_CHATTER)\r
- fprintf(m_output, "_ignored: %s same size\n", targetRelativePath);\r
+ fprintf(m_output, "_ignored: %s same size\n",\r
+ targetRelativePath);\r
continue;\r
}\r
// target younger than source?\r
- int diff = int(m_statInfo.st_mtime - entry->filetimeToTime(entry->modified()));\r
- if (! ignoreDate && m_statInfo.st_mtime - entry->filetimeToTime(entry->modified())\r
- <= maxFileTimeDiff) {\r
+ int diff = int(\r
+ m_statInfo.st_mtime\r
+ - entry->filetimeToTime(entry->modified()));\r
+ if (!ignoreDate\r
+ && m_statInfo.st_mtime\r
+ - entry->filetimeToTime(entry->modified())\r
+ <= maxFileTimeDiff) {\r
if (m_verboseLevel >= V_CHATTER)\r
- fprintf(m_output, "=ignored: %s same time\n", targetRelativePath);\r
+ fprintf(m_output, "=ignored: %s same time\n",\r
+ targetRelativePath);\r
continue;\r
}\r
}\r
files++;\r
sumSizes += entry->fileSize();\r
if (m_verboseLevel >= V_NORMAL)\r
- fprintf(m_output, "%c%s%s\n", targetExists ? '!' : '+', targetRelativePath,\r
- dry ? " would be copied" : "");\r
- if (! dry)\r
+ fprintf(m_output, "%c%s%s\n", targetExists ? '!' : '+',\r
+ targetRelativePath, dry ? " would be copied" : "");\r
+ if (!dry)\r
copyFile(entry, targetFile.str());\r
}\r
treeFiles += m_traverser.files();\r
treeDirs += m_traverser.directories();\r
- treeSumSizes+= m_traverser.sizes();\r
+ treeSumSizes += m_traverser.sizes();\r
}\r
- if (m_verboseLevel >= V_SUMMARY){\r
+ if (m_verboseLevel >= V_SUMMARY) {\r
int duration = int(time(NULL) - m_start);\r
- fprintf(m_output, i18n(\r
- "=== copied: %02d:%02d sec %7d file(s) %12.6f MByte (%.3f MB/sec).\n"\r
- "=== tree: %5d dir(s) %7d file(s) %12.6f MByte\n"),\r
- duration / 60, duration % 60, files, sumSizes / 1E6,\r
- sumSizes / 1E6 / (duration == 0 ? 1 : duration),\r
- treeDirs, treeFiles, treeSumSizes / 1E6);\r
+ fprintf(m_output,\r
+ i18n(\r
+ "=== copied: %02d:%02d sec %7d file(s) %12.6f MByte (%.3f MB/sec).\n"\r
+ "=== tree: %5d dir(s) %7d file(s) %12.6f MByte\n"),\r
+ duration / 60, duration % 60, files, sumSizes / 1E6,\r
+ sumSizes / 1E6 / (duration == 0 ? 1 : duration), treeDirs,\r
+ treeFiles, treeSumSizes / 1E6);\r
}\r
}\r
\r
* @param logger logger for error handling\r
*/\r
ReDirWhich::ReDirWhich(ReLogger* logger) :\r
- ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger)\r
-{\r
+ ReTool(s_batchUsage, s_batchExamples, 0, 0, 0, true, logger) {\r
// no standard options:\r
- m_programArgs.addBool("all",\r
- i18n("all files will be found, not only the first"),\r
- 'a', "all", false);\r
- m_programArgs.addString("list",\r
- i18n("a path list (separator see option 'separator'"),\r
- 'l', "list", false, NULL);\r
+ m_programArgs.addBool("all",\r
+ i18n("all files will be found, not only the first"), 'a', "all", false);\r
+ m_programArgs.addString("list",\r
+ i18n("a path list (separator see option 'separator'"), 'l', "list",\r
+ false, NULL);\r
m_programArgs.addString("separator",\r
i18n("separator between the path elements"),\r
's', "separator", false,\r
#elif defined __WIN32__\r
";"\r
#endif\r
- );\r
- m_programArgs.addString("variable",\r
- i18n("variable with the path list"),\r
- 'v', "variable", false, "PATH");\r
+ );\r
+ m_programArgs.addString("variable", i18n("variable with the path list"),\r
+ 'v', "variable", false, "PATH");\r
m_hasStandardArgs = false;\r
}\r
\r
/**\r
* Creates the batch file.\r
*/\r
-void ReDirWhich::doIt(){\r
+void ReDirWhich::doIt() {\r
ReByteBuffer value, path;\r
bool all = false;\r
ReStringList items;\r
char sep = 0;\r
m_programArgs.getString("list", path);\r
- if (path.length() == 0){\r
+ if (path.length() == 0) {\r
m_programArgs.getString("variable", value);\r
if (getenv(value.str()) == NULL)\r
help("Umgebungsvariable nicht definiert: ", value.str());\r
items.split(path.str(), sep);\r
struct stat info;\r
ReByteBuffer full;\r
- for (int ix = 0; ix < m_programArgs.getArgCount(); ix++){\r
+ for (int ix = 0; ix < m_programArgs.getArgCount(); ix++) {\r
bool found = false;\r
\r
ReByteBuffer arg(m_programArgs.getArg(ix));\r
- for (size_t ixItem = 0; ixItem < items.count(); ixItem++){\r
+ for (size_t ixItem = 0; ixItem < items.count(); ixItem++) {\r
full.set(items.strOf(ixItem));\r
- if (arg.indexOf('*') < 0){\r
+ if (arg.indexOf('*') < 0) {\r
full.ensureLastChar(OS_SEPARATOR_CHAR);\r
full.append(arg);\r
found = stat(full.str(), &info) == 0;\r
printf("%s\n", full.str());\r
} else {\r
ReDirectory dir(full.str());\r
- if (dir.findFirst(arg.str(), false)){\r
+ if (dir.findFirst(arg.str(), false)) {\r
do {\r
- printf("%s%c%s\n", full.str(), OS_SEPARATOR_CHAR, dir.currentFile());\r
- } while(dir.findNext());\r
+ printf("%s%c%s\n", full.str(), OS_SEPARATOR_CHAR,\r
+ dir.currentFile());\r
+ } while (dir.findNext());\r
}\r
}\r
- if (found && ! all)\r
+ if (found && !all)\r
break;\r
}\r
}\r
* @param part the part to test\r
* @return <code>true</code>: part is a prefix of full\r
*/\r
-static bool isArg(const char* full, const char* part){\r
- ReByteBuffer fullArg(full);\r
- bool rc = fullArg.startsWith(part, -1);\r
- return rc;\r
+static bool isArg(const char* full, const char* part) {\r
+ ReByteBuffer fullArg(full);\r
+ bool rc = fullArg.startsWith(part, -1);\r
+ return rc;\r
}\r
\r
/**\r
* @param argc the number of arguments\r
* @param argav the argument vector\r
*/\r
-void ReDirTools::help(int argc, const char* argv[]){\r
- if (argc <= 1)\r
- printField(s_helpSummary);\r
- else {\r
- argc--;\r
- argv++;\r
- const char* arg0 = argv[0];\r
- if (isArg("batch", arg0)){\r
- ReDirBatch batch(m_logger);\r
- batch.help(NULL);\r
- } else if (isArg("list", arg0)){\r
- ReDirList list(m_logger);\r
- list.help(NULL);\r
- } else if (isArg("help", arg0)){\r
- printField(s_helpSummary);\r
- } else if (isArg("md5", arg0)){\r
- ReDirMD5 md5(m_logger);\r
- md5.help(NULL);\r
- } else if (isArg("statistic", arg0)){\r
- ReDirStatistic stat(m_logger);\r
- stat.help(NULL);\r
- } else if (isArg("test", arg0)){\r
- void testAll();\r
- testAll();\r
- } else if (isArg("touch", arg0)){\r
- ReDirTouch touch(m_logger);\r
- touch.help(NULL);\r
- } else if (isArg("which", arg0)){\r
- ReDirWhich which(m_logger);\r
- which.help(NULL);\r
- } else\r
- printf("+++ unknown sub command: %s\n", arg0);\r
- }\r
+void ReDirTools::help(int argc, const char* argv[]) {\r
+ if (argc <= 1)\r
+ printField(s_helpSummary);\r
+ else {\r
+ argc--;\r
+ argv++;\r
+ const char* arg0 = argv[0];\r
+ if (isArg("batch", arg0)) {\r
+ ReDirBatch batch(m_logger);\r
+ batch.help(NULL);\r
+ } else if (isArg("list", arg0)) {\r
+ ReDirList list(m_logger);\r
+ list.help(NULL);\r
+ } else if (isArg("help", arg0)) {\r
+ printField(s_helpSummary);\r
+ } else if (isArg("md5", arg0)) {\r
+ ReDirMD5 md5(m_logger);\r
+ md5.help(NULL);\r
+ } else if (isArg("statistic", arg0)) {\r
+ ReDirStatistic stat(m_logger);\r
+ stat.help(NULL);\r
+ } else if (isArg("test", arg0)) {\r
+ void testAll();\r
+ testAll();\r
+ } else if (isArg("touch", arg0)) {\r
+ ReDirTouch touch(m_logger);\r
+ touch.help(NULL);\r
+ } else if (isArg("which", arg0)) {\r
+ ReDirWhich which(m_logger);\r
+ which.help(NULL);\r
+ } else\r
+ printf("+++ unknown sub command: %s\n", arg0);\r
+ }\r
}\r
\r
/**\r
* @param argv the argument vector\r
* @param tool the tool which realizes the command\r
*/\r
-void ReDirTools::run(int argc, const char* argv[], ReTool& tool){\r
+void ReDirTools::run(int argc, const char* argv[], ReTool& tool) {\r
tool.run(argc, argv);\r
}\r
/**\r
* @param argc the number of arguments\r
* @param orgArgv the argument vector\r
*/\r
-int ReDirTools::main(int argc, char* orgArgv[]){\r
- ReDirTools tools;\r
- const char** argv = (const char**) orgArgv;\r
- if (argc < 2){\r
- tools.help(0, argv);\r
- exit(1);\r
- }\r
- argc--;\r
- argv++;\r
+int ReDirTools::main(int argc, char* orgArgv[]) {\r
+ ReDirTools tools;\r
+ const char** argv = (const char**) orgArgv;\r
+ if (argc < 2) {\r
+ tools.help(0, argv);\r
+ exit(1);\r
+ }\r
+ argc--;\r
+ argv++;\r
m_logger = ReLogger::globalLogger();\r
- const char* arg0 = argv[0];\r
- if (isArg("batch", arg0))\r
- ReDirBatch(m_logger).run(argc, argv);\r
- else if (isArg("help", arg0))\r
- tools.help(argc, argv);\r
- else if (isArg("list", arg0))\r
- ReDirList(m_logger).run(argc, argv);\r
- else if (isArg("md5", arg0))\r
- ReDirMD5(m_logger).run(argc, argv);\r
- else if (isArg("statistic", arg0))\r
- ReDirStatistic(m_logger).run(argc, argv);\r
- else if (isArg("synchronize", arg0))\r
- ReDirSync(m_logger).run(argc, argv);\r
- else if (isArg("touch", arg0))\r
- ReDirTouch(m_logger).run(argc, argv);\r
- else if (isArg("which", arg0))\r
- ReDirWhich(m_logger).run(argc, argv);\r
- else if (isArg("test", arg0)){\r
- void testAll();\r
- testAll();\r
- }else\r
- tools.usage("unknown command: ", argv[1]);\r
- return 0;\r
+ const char* arg0 = argv[0];\r
+ if (isArg("batch", arg0))\r
+ ReDirBatch(m_logger).run(argc, argv);\r
+ else if (isArg("help", arg0))\r
+ tools.help(argc, argv);\r
+ else if (isArg("list", arg0))\r
+ ReDirList(m_logger).run(argc, argv);\r
+ else if (isArg("md5", arg0))\r
+ ReDirMD5(m_logger).run(argc, argv);\r
+ else if (isArg("statistic", arg0))\r
+ ReDirStatistic(m_logger).run(argc, argv);\r
+ else if (isArg("synchronize", arg0))\r
+ ReDirSync(m_logger).run(argc, argv);\r
+ else if (isArg("touch", arg0))\r
+ ReDirTouch(m_logger).run(argc, argv);\r
+ else if (isArg("which", arg0))\r
+ ReDirWhich(m_logger).run(argc, argv);\r
+ else if (isArg("test", arg0)) {\r
+ void testAll();\r
+ testAll();\r
+ } else\r
+ tools.usage("unknown command: ", argv[1]);\r
+ return 0;\r
}\r
\r
#ifndef OS_DIRTOOLS_HPP_
#define OS_DIRTOOLS_HPP_
-class ReDirOptions : public ReTraceUnit{
+class ReDirOptions: public ReTraceUnit {
public:
enum VerboseLevel {
V_UNDEF,
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;
};
/**
* 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);
@param name can be changed and recovered!
@return <code>true</code>: 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
}
};
-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);
/**
* 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);
/**
* 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);
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;
/**
* 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();
};
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_ */
#endif\r
\r
enum RELOC_TRAVERSER {\r
- LC_RIGHTS_AS_STRING_1 = LC_TRAVERSER + 1, // 50401\r
+ LC_RIGHTS_AS_STRING_1 = LC_TRAVERSER + 1, // 50401\r
LC_RIGHTS_AS_STRING_2, // 50402\r
LC_RIGHTS_AS_STRING_3, // 50403\r
LC_GET_PRIVILEGE_1, // 50404\r
\r
/**\r
* Constructor.\r
-*/\r
+ */\r
ReDirStatus_t::ReDirStatus_t(ReLogger* logger) :\r
- m_path(),\r
- m_fullName(),\r
- m_passNo(0),\r
- m_logger(logger),\r
+m_path(),\r
+m_fullName(),\r
+m_passNo(0),\r
+m_logger(logger),\r
#ifdef __linux__\r
- m_handle(NULL),\r
- m_data(NULL)\r
- //m_status;\r
+m_handle(NULL),\r
+m_data(NULL)\r
+//m_status;\r
#elif defined WIN32\r
- m_handle(INVALID_HANDLE_VALUE),\r
- //m_data;\r
- m_getPrivilege(true)\r
+m_handle(INVALID_HANDLE_VALUE),\r
+//m_data;\r
+m_getPrivilege(true)\r
#endif\r
{\r
#ifdef __linux__\r
*/\r
const ReFileTime_t* ReDirStatus_t::accessed() {\r
#ifdef __linux__\r
- return &(getStatus()->st_atim);\r
+ return &(getStatus()->st_atim);\r
#elif defined __WIN32__\r
- return &m_data.ftLastAccessTime;\r
+ return &m_data.ftLastAccessTime;\r
#endif\r
}\r
\r
*/\r
ReFileSize_t ReDirStatus_t::fileSize() {\r
#ifdef __linux__\r
- return getStatus()->st_size;\r
+ return getStatus()->st_size;\r
#elif defined __WIN32__\r
- return ((int64_t) m_data.nFileSizeHigh << 32) + m_data.nFileSizeLow;\r
+ return ((int64_t) m_data.nFileSizeHigh << 32) + m_data.nFileSizeLow;\r
#endif\r
}\r
\r
* @return <code>buffer.str()</code> (for chaining)\r
*/\r
const char* ReDirStatus_t::filetimeAsString(ReByteBuffer& buffer) {\r
- return filetimeToString(modified(), buffer);\r
+ return filetimeToString(modified(), buffer);\r
}\r
\r
/**\r
* @param buffer OUT: the buffer for the string\r
* @return <code>buffer.str()</code>, e.g. "2014.01.07 02:59:43"\r
*/\r
-const char* ReDirStatus_t::filetimeToString(const ReFileTime_t* time, ReByteBuffer& buffer){\r
- time_t time1 = filetimeToTime(time);\r
- struct tm* time2 = localtime(&time1);\r
- buffer.setLength(4+2*2+2*2+1+3*2+2*1);\r
- strftime(buffer.buffer(), buffer.length(), "%Y.%m.%d %H:%M:%S", time2);\r
+const char* ReDirStatus_t::filetimeToString(const ReFileTime_t* time,\r
+ ReByteBuffer& buffer) {\r
+ time_t time1 = filetimeToTime(time);\r
+ struct tm* time2 = localtime(&time1);\r
+ buffer.setLength(4 + 2 * 2 + 2 * 2 + 1 + 3 * 2 + 2 * 1);\r
+ strftime(buffer.buffer(), buffer.length(), "%Y.%m.%d %H:%M:%S", time2);\r
return buffer.str();\r
}\r
\r
* @param filetime the filetime to convert\r
* @return the count of seconds since 1.1.1970\r
*/\r
-time_t ReDirStatus_t::filetimeToTime(const ReFileTime_t* filetime){\r
+time_t ReDirStatus_t::filetimeToTime(const ReFileTime_t* filetime) {\r
#ifdef __linux__\r
- return filetime->tv_sec;\r
+ return filetime->tv_sec;\r
#elif defined __WIN32__\r
- // 64-bit arithmetic:\r
- LARGE_INTEGER date, adjust;\r
- date.HighPart = filetime->dwHighDateTime;\r
- date.LowPart = filetime->dwLowDateTime;\r
- // 100-nanoseconds = milliseconds * 10000\r
- adjust.QuadPart = 11644473600000 * 10000;\r
- // removes the diff between 1970 and 1601\r
- date.QuadPart -= adjust.QuadPart;\r
- // converts back from 100-nanoseconds to seconds\r
- time_t rc = (time_t) (date.QuadPart / 10000000);\r
+ // 64-bit arithmetic:\r
+ LARGE_INTEGER date, adjust;\r
+ date.HighPart = filetime->dwHighDateTime;\r
+ date.LowPart = filetime->dwLowDateTime;\r
+ // 100-nanoseconds = milliseconds * 10000\r
+ adjust.QuadPart = 11644473600000 * 10000;\r
+ // removes the diff between 1970 and 1601\r
+ date.QuadPart -= adjust.QuadPart;\r
+ // converts back from 100-nanoseconds to seconds\r
+ time_t rc = (time_t) (date.QuadPart / 10000000);\r
return rc;\r
#endif\r
}\r
*\r
* @return <code>true</code>: success\r
*/\r
-bool ReDirStatus_t::findFirst(){\r
+bool ReDirStatus_t::findFirst() {\r
bool rc = false;\r
#if defined __linux__\r
if (m_handle != NULL)\r
- closedir(m_handle);\r
+ closedir(m_handle);\r
m_handle = opendir(m_path.str());\r
rc = m_handle != NULL && (m_data = readdir(m_handle)) != NULL;\r
m_status.st_ino = 0;\r
#elif defined __WIN32__\r
if (m_handle != INVALID_HANDLE_VALUE)\r
- FindClose(m_handle);\r
+ FindClose(m_handle);\r
ReByteBuffer thePath(m_path);\r
thePath.append(m_path.lastChar() == '\\' ? "*" : "\\*");\r
m_handle = FindFirstFileA(thePath.str(), &m_data);\r
*\r
* @return <code>true</code>: success\r
*/\r
-bool ReDirStatus_t::findNext(){\r
+bool ReDirStatus_t::findNext() {\r
#if defined __linux__\r
bool rc = m_handle != NULL && (m_data = readdir(m_handle)) != NULL;\r
m_status.st_ino = 0;\r
/**\r
* Frees the resources of an instance.\r
*/\r
-void ReDirStatus_t::freeEntry(){\r
+void ReDirStatus_t::freeEntry() {\r
#if defined __linux__\r
- if (m_handle != NULL){\r
+ if (m_handle != NULL) {\r
closedir(m_handle);\r
m_handle = NULL;\r
}\r
#elif defined __WIN32__\r
- if (m_handle != INVALID_HANDLE_VALUE){\r
+ if (m_handle != INVALID_HANDLE_VALUE) {\r
FindClose(m_handle);\r
m_handle = INVALID_HANDLE_VALUE;\r
}\r
*\r
* @return the filename with path\r
*/\r
-const char* ReDirStatus_t::fullName(){\r
+const char* ReDirStatus_t::fullName() {\r
if (m_fullName.length() == 0)\r
m_fullName.set(m_path).append(node(), -1);\r
return m_fullName.str();\r
\r
#if defined __WIN32__\r
/** Gets the name of the file owner.\r
-*\r
-* @param handle file handle (see <code>CreateFile()</code>)\r
-* @param name OUT: the owner: [domain\\]name\r
-* @return <code>true</code>: success\r
-*/\r
+ *\r
+ * @param handle file handle (see <code>CreateFile()</code>)\r
+ * @param name OUT: the owner: [domain\\]name\r
+ * @return <code>true</code>: success\r
+ */\r
bool ReDirStatus_t::getFileOwner(HANDLE handle, const char* file,\r
- ReByteBuffer& name, ReLogger* logger){\r
+ ReByteBuffer& name, ReLogger* logger) {\r
bool rc = false;\r
PSID pSidOwner = NULL;\r
PSECURITY_DESCRIPTOR pSD = NULL;\r
if (GetSecurityInfo(handle, SE_FILE_OBJECT,\r
- OWNER_SECURITY_INFORMATION, &pSidOwner, NULL, NULL, NULL, &pSD) != ERROR_SUCCESS) {\r
+ OWNER_SECURITY_INFORMATION, &pSidOwner, NULL, NULL, NULL, &pSD) != ERROR_SUCCESS) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_FILE_OWNER_1,\r
- "GetSecurityInfo($1): $2").arg(file).arg((int) GetLastError()).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_FILE_OWNER_1,\r
+ "GetSecurityInfo($1): $2").arg(file).arg((int) GetLastError()).end();\r
} else {\r
char accountName[128];\r
char domainName[128];\r
DWORD dwAcctName = sizeof accountName;\r
DWORD dwDomainName = sizeof domainName;\r
SID_NAME_USE eUse = SidTypeUnknown;\r
- if (! LookupAccountSid(NULL, pSidOwner, accountName, &dwAcctName, domainName, \r
- &dwDomainName, &eUse)){\r
+ if (! LookupAccountSid(NULL, pSidOwner, accountName, &dwAcctName, domainName,\r
+ &dwDomainName, &eUse)) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_SECURITY, LC_GET_FILE_OWNER_2,\r
- "LookupAccountSid(): $1").arg((int) GetLastError()).end();\r
+ logger->sayF(LOG_ERROR | CAT_SECURITY, LC_GET_FILE_OWNER_2,\r
+ "LookupAccountSid(): $1").arg((int) GetLastError()).end();\r
} else {\r
if (dwDomainName > 0)\r
- name.append(domainName).appendChar('\\');\r
+ name.append(domainName).appendChar('\\');\r
name.append(accountName);\r
rc = true;\r
}\r
\r
#if defined __WIN32__\r
/** Tries to get a privilege.\r
-*\r
-* @param privilege the name of the privilege, e.g. "SeBackup"\r
-* @param logger logger for error logging\r
-*/\r
-bool ReDirStatus_t::getPrivilege(const char* privilege, ReLogger* logger){\r
+ *\r
+ * @param privilege the name of the privilege, e.g. "SeBackup"\r
+ * @param logger logger for error logging\r
+ */\r
+bool ReDirStatus_t::getPrivilege(const char* privilege, ReLogger* logger) {\r
bool rc = false;\r
LUID luidPrivilege;\r
HANDLE hAccessToken;\r
- if (! OpenProcessToken (GetCurrentProcess(), \r
- TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hAccessToken)){\r
+ if (! OpenProcessToken (GetCurrentProcess(),\r
+ TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hAccessToken)) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_1,\r
- "OpenProcessToken(): $1").arg((int) GetLastError()).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_1,\r
+ "OpenProcessToken(): $1").arg((int) GetLastError()).end();\r
} else if (! LookupPrivilegeValue (NULL, SE_BACKUP_NAME, &luidPrivilege)) {\r
if (logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_2,\r
- "LookupPrivilegeValue(): $1").arg((int) GetLastError()).end(); \r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_2,\r
+ "LookupPrivilegeValue(): $1").arg((int) GetLastError()).end();\r
} else {\r
- TOKEN_PRIVILEGES tpPrivileges;\r
- tpPrivileges.PrivilegeCount = 1;\r
- tpPrivileges.Privileges[0].Luid = luidPrivilege;\r
- tpPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\r
- if (AdjustTokenPrivileges (hAccessToken, FALSE, &tpPrivileges, \r
+ TOKEN_PRIVILEGES tpPrivileges;\r
+ tpPrivileges.PrivilegeCount = 1;\r
+ tpPrivileges.Privileges[0].Luid = luidPrivilege;\r
+ tpPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\r
+ if (AdjustTokenPrivileges (hAccessToken, FALSE, &tpPrivileges,\r
0, NULL, NULL) == 0)\r
- rc = true;\r
+ rc = true;\r
else {\r
int error = GetLastError();\r
if (error != 1300 && logger != NULL)\r
- logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_3,\r
- "AdjustTokenPrivileges(): $1").arg((int) GetLastError()).end();\r
+ logger->sayF(LOG_ERROR | CAT_FILE, LC_GET_PRIVILEGE_3,\r
+ "AdjustTokenPrivileges(): $1").arg((int) GetLastError()).end();\r
}\r
- }\r
+ }\r
return rc;\r
}\r
#endif /* __WIN32__ */\r
*/\r
bool ReDirStatus_t::isDirectory() {\r
#ifdef __linux__\r
- return m_data->d_type == DT_DIR\r
- || (m_data->d_type == DT_UNKNOWN && S_ISDIR(getStatus()->st_mode));\r
+ return m_data->d_type == DT_DIR\r
+ || (m_data->d_type == DT_UNKNOWN && S_ISDIR(getStatus()->st_mode));\r
#elif defined __WIN32__\r
- return 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);\r
+ return 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);\r
#endif\r
}\r
\r
*\r
* @return <code>true</code>: an ignorable entry has been found\r
*/\r
-bool ReDirStatus_t::isDotDir() const{\r
+bool ReDirStatus_t::isDotDir() const {\r
#ifdef __linux__\r
- bool rc = m_data == NULL || (m_data->d_name[0] == '.' && (m_data->d_name[1] == '\0'\r
- || (m_data->d_name[1] == '.' && m_data->d_name[2] == '\0')));\r
+ bool rc = m_data == NULL || (m_data->d_name[0] == '.' && (m_data->d_name[1] == '\0'\r
+ || (m_data->d_name[1] == '.' && m_data->d_name[2] == '\0')));\r
#elif defined __WIN32__\r
- bool rc = m_data.cFileName[0] == '.' && (m_data.cFileName[1] == '\0'\r
- || (m_data.cFileName[1] == '.' && m_data.cFileName[2] == '\0'));\r
+ bool rc = m_data.cFileName[0] == '.' && (m_data.cFileName[1] == '\0'\r
+ || (m_data.cFileName[1] == '.' && m_data.cFileName[2] == '\0'));\r
#endif\r
- return rc;\r
+ return rc;\r
}\r
\r
/**\r
bool ReDirStatus_t::isLink() {\r
bool rc;\r
#ifdef __linux__\r
- rc = m_data->d_type == DT_LNK\r
- || (m_data->d_type == DT_UNKNOWN && S_ISLNK(getStatus()->st_mode));\r
+ rc = m_data->d_type == DT_LNK\r
+ || (m_data->d_type == DT_UNKNOWN && S_ISLNK(getStatus()->st_mode));\r
#elif defined __WIN32__\r
- rc = 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT);\r
+ rc = 0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT);\r
#endif\r
- return rc;\r
+ return rc;\r
}\r
/**\r
* Tests whether the instance is a "normal" file.\r
*/\r
bool ReDirStatus_t::isRegular() {\r
#ifdef __linux__\r
- return m_data->d_type == DT_REG\r
- || (m_data->d_type == DT_UNKNOWN && S_ISREG(getStatus()->st_mode));\r
+ return m_data->d_type == DT_REG\r
+ || (m_data->d_type == DT_UNKNOWN && S_ISREG(getStatus()->st_mode));\r
#elif defined __WIN32__\r
- return 0 == (m_data.dwFileAttributes & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE));\r
+ return 0 == (m_data.dwFileAttributes & (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE));\r
#endif\r
}\r
/**\r
*/\r
const ReFileTime_t* ReDirStatus_t::modified() {\r
#ifdef __linux__\r
- return &(getStatus()->st_mtim);\r
+ return &(getStatus()->st_mtim);\r
#elif defined __WIN32__\r
- return &m_data.ftLastWriteTime;\r
+ return &m_data.ftLastWriteTime;\r
#endif\r
}\r
\r
*\r
* @return the name of the current file.\r
*/\r
-const char* ReDirStatus_t::node() const{\r
+const char* ReDirStatus_t::node() const {\r
#ifdef __linux__\r
- return m_data->d_name;\r
+ return m_data->d_name;\r
#elif defined __WIN32__\r
- return m_data.cFileName;\r
+ return m_data.cFileName;\r
#endif\r
}\r
\r
-inline void addRight(int mode, ReByteBuffer& buffer){\r
+inline void addRight(int mode, ReByteBuffer& buffer) {\r
char right;\r
- switch(mode & 7){\r
- case 1:\r
- right = 'x';\r
- break;\r
- case 2:\r
- right = 'w';\r
- break;\r
- case 3:\r
- right = 'X';\r
- break;\r
- case 4:\r
- right = 'r';\r
- break;\r
- case 5:\r
- right = 'R';\r
- break;\r
- case 6:\r
- right = 'W';\r
- break;\r
- case 7:\r
- right = 'A';\r
- break;\r
- default:\r
- right = '-';\r
- break;\r
+ switch (mode & 7) {\r
+ case 1:\r
+ right = 'x';\r
+ break;\r
+ case 2:\r
+ right = 'w';\r
+ break;\r
+ case 3:\r
+ right = 'X';\r
+ break;\r
+ case 4:\r
+ right = 'r';\r
+ break;\r
+ case 5:\r
+ right = 'R';\r
+ break;\r
+ case 6:\r
+ right = 'W';\r
+ break;\r
+ case 7:\r
+ right = 'A';\r
+ break;\r
+ default:\r
+ right = '-';\r
+ break;\r
}\r
buffer.appendChar(right);\r
}\r
-inline void addId(const char* id, int maxLength, ReByteBuffer& buffer){\r
+inline void addId(const char* id, int maxLength, ReByteBuffer& buffer) {\r
int length = strlen(id);\r
if (length == maxLength)\r
buffer.append(id, length);\r
* @param ownerWidth the width for group/owner\r
* @return <code>buffer.str()</code> (for chaining)\r
*/\r
-const char* ReDirStatus_t::rightsAsString(ReByteBuffer& buffer, bool numerical, \r
- int ownerWidth) {\r
- buffer.setLength(0);\r
+const char* ReDirStatus_t::rightsAsString(ReByteBuffer& buffer, bool numerical,\r
+ int ownerWidth) {\r
+ buffer.setLength(0);\r
#if defined __linux__\r
- if (numerical){\r
+ if (numerical) {\r
buffer.appendInt(getStatus()->st_mode & ALLPERMS, "%04o");\r
buffer.appendInt(getStatus()->st_uid, " %4d");\r
buffer.appendInt(getStatus()->st_gid, " %4d");\r
buffer.appendChar(' ');\r
struct passwd* passwd = getpwuid(getStatus()->st_uid);\r
if (passwd == NULL)\r
- buffer.appendInt(getStatus()->st_uid, "%4d");\r
+ buffer.appendInt(getStatus()->st_uid, "%4d");\r
else\r
- addId(passwd->pw_name, 5, buffer);\r
+ addId(passwd->pw_name, 5, buffer);\r
buffer.appendChar(' ');\r
struct group* group = getgrgid(getStatus()->st_gid);\r
if (group == NULL)\r
- buffer.appendInt(getStatus()->st_gid, "%4d");\r
+ buffer.appendInt(getStatus()->st_gid, "%4d");\r
else\r
- addId(group->gr_name, 5, buffer);\r
+ addId(group->gr_name, 5, buffer);\r
buffer.appendChar(' ');\r
}\r
#elif defined __WIN32__\r
const char* name = fullName();\r
HANDLE handle = INVALID_HANDLE_VALUE;\r
- if (! isDirectory()){\r
+ if (! isDirectory()) {\r
if ( (handle = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL,\r
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)\r
- m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_1,\r
- "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end();\r
- } else if (m_getPrivilege){\r
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)\r
+ m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_1,\r
+ "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end();\r
+ } else if (m_getPrivilege) {\r
// we try only one time:\r
m_getPrivilege = false;\r
- if (getPrivilege(SE_BACKUP_NAME, m_logger)){\r
- if ( (handle = CreateFile(name, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, \r
- NULL)) != INVALID_HANDLE_VALUE)\r
- m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_2,\r
- "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end();\r
+ if (getPrivilege(SE_BACKUP_NAME, m_logger)) {\r
+ if ( (handle = CreateFile(name, 0, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,\r
+ NULL)) != INVALID_HANDLE_VALUE)\r
+ m_logger->sayF(LOG_ERROR | CAT_FILE, LC_RIGHTS_AS_STRING_2,\r
+ "CreateFile($1): $2").arg(name).arg((int) GetLastError()).end();\r
}\r
\r
}\r
ReByteBuffer owner;\r
if (handle != INVALID_HANDLE_VALUE)\r
- getFileOwner(handle, name, owner, m_logger);\r
+ getFileOwner(handle, name, owner, m_logger);\r
CloseHandle(handle);\r
buffer.appendFix(owner.str(), owner.length(), ownerWidth, ownerWidth);\r
#endif\r
- return buffer.str();\r
+ return buffer.str();\r
}\r
\r
/**\r
* @param time the unix time (secondes since 1.1.1970)\r
* @param filetime OUT: the OS specific filetime\r
*/\r
-void ReDirStatus_t::timeToFiletime(time_t time, ReFileTime_t& filetime){\r
+void ReDirStatus_t::timeToFiletime(time_t time, ReFileTime_t& filetime) {\r
#ifdef __linux__\r
- filetime.tv_sec = time;\r
+ filetime.tv_sec = time;\r
filetime.tv_nsec = 0;\r
#elif defined __WIN32__\r
- LONGLONG ll = Int32x32To64(time, 10000000) + 116444736000000000;\r
- filetime.dwLowDateTime = (DWORD)ll;\r
- filetime.dwHighDateTime = ll >> 32;\r
+ LONGLONG ll = Int32x32To64(time, 10000000) + 116444736000000000;\r
+ filetime.dwLowDateTime = (DWORD)ll;\r
+ filetime.dwHighDateTime = ll >> 32;\r
#endif\r
}\r
/**\r
* Returns the type of the entry.\r
* return the file type, e.g. TF_REGULAR\r
*/\r
-ReDirStatus_t::Type_t ReDirStatus_t::type(){\r
- Type_t rc = TF_UNDEF;\r
+ReDirStatus_t::Type_t ReDirStatus_t::type() {\r
+ Type_t rc = TF_UNDEF;\r
#if defined __linux__\r
int flags = getStatus()->st_mode;\r
- if (S_ISDIR(flags))\r
- rc = TF_SUBDIR;\r
- else if (flags == 0 || S_ISREG(flags))\r
- rc = TF_REGULAR;\r
- else if (S_ISLNK(flags))\r
- rc = TF_LINK;\r
- else if (S_ISCHR(flags))\r
- rc = TF_CHAR;\r
- else if (S_ISBLK(flags))\r
- rc = TF_BLOCK;\r
- else if (S_ISFIFO(flags))\r
- rc = TF_PIPE;\r
- else if (S_ISSOCK(flags))\r
- rc = TF_SOCKET;\r
- else\r
- rc = TF_OTHER;\r
+ if (S_ISDIR(flags))\r
+ rc = TF_SUBDIR;\r
+ else if (flags == 0 || S_ISREG(flags))\r
+ rc = TF_REGULAR;\r
+ else if (S_ISLNK(flags))\r
+ rc = TF_LINK;\r
+ else if (S_ISCHR(flags))\r
+ rc = TF_CHAR;\r
+ else if (S_ISBLK(flags))\r
+ rc = TF_BLOCK;\r
+ else if (S_ISFIFO(flags))\r
+ rc = TF_PIPE;\r
+ else if (S_ISSOCK(flags))\r
+ rc = TF_SOCKET;\r
+ else\r
+ rc = TF_OTHER;\r
#elif defined __WIN32__\r
- int flags = (m_data.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY\r
- | FILE_ATTRIBUTE_HIDDEN\r
- | FILE_ATTRIBUTE_SYSTEM\r
- | FILE_ATTRIBUTE_ARCHIVE\r
- | FILE_ATTRIBUTE_NORMAL\r
- | FILE_ATTRIBUTE_TEMPORARY\r
- | FILE_ATTRIBUTE_SPARSE_FILE\r
- | FILE_ATTRIBUTE_COMPRESSED\r
- | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED\r
- | FILE_ATTRIBUTE_ENCRYPTED\r
- | FILE_ATTRIBUTE_HIDDEN));\r
-\r
- if (0 == flags)\r
- rc = TF_REGULAR;\r
- else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)){\r
- rc = (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))\r
- ? TF_LINK_DIR : TF_SUBDIR;\r
- } else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))\r
- rc = TF_LINK;\r
- else\r
- rc = TF_OTHER;\r
+ int flags = (m_data.dwFileAttributes & ~(FILE_ATTRIBUTE_READONLY\r
+ | FILE_ATTRIBUTE_HIDDEN\r
+ | FILE_ATTRIBUTE_SYSTEM\r
+ | FILE_ATTRIBUTE_ARCHIVE\r
+ | FILE_ATTRIBUTE_NORMAL\r
+ | FILE_ATTRIBUTE_TEMPORARY\r
+ | FILE_ATTRIBUTE_SPARSE_FILE\r
+ | FILE_ATTRIBUTE_COMPRESSED\r
+ | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED\r
+ | FILE_ATTRIBUTE_ENCRYPTED\r
+ | FILE_ATTRIBUTE_HIDDEN));\r
+\r
+ if (0 == flags)\r
+ rc = TF_REGULAR;\r
+ else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\r
+ rc = (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))\r
+ ? TF_LINK_DIR : TF_SUBDIR;\r
+ } else if (0 != (m_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))\r
+ rc = TF_LINK;\r
+ else\r
+ rc = TF_OTHER;\r
#endif\r
- return rc;\r
+ return rc;\r
}\r
\r
/**\r
*\r
* @return the filetype, e.g. 'd' for a directory\r
*/\r
-char ReDirStatus_t::typeAsChar(){\r
+char ReDirStatus_t::typeAsChar() {\r
char rc = ' ';\r
- switch(type()){\r
- case TF_REGULAR:\r
- rc = ' ';\r
- break;\r
- case TF_LINK:\r
- rc = 'l';\r
- break;\r
- case TF_SUBDIR:\r
- rc = 'd';\r
- break;\r
- case TF_CHAR:\r
- rc = 'c';\r
- break;\r
- case TF_BLOCK:\r
- rc = 'b';\r
- break;\r
- case TF_PIPE:\r
- rc = 'p';\r
- break;\r
- case TF_SOCKET:\r
- rc = 's';\r
- break;\r
- default:\r
- rc = 'o';\r
- break;\r
+ switch (type()) {\r
+ case TF_REGULAR:\r
+ rc = ' ';\r
+ break;\r
+ case TF_LINK:\r
+ rc = 'l';\r
+ break;\r
+ case TF_SUBDIR:\r
+ rc = 'd';\r
+ break;\r
+ case TF_CHAR:\r
+ rc = 'c';\r
+ break;\r
+ case TF_BLOCK:\r
+ rc = 'b';\r
+ break;\r
+ case TF_PIPE:\r
+ rc = 'p';\r
+ break;\r
+ case TF_SOCKET:\r
+ rc = 's';\r
+ break;\r
+ default:\r
+ rc = 'o';\r
+ break;\r
}\r
return rc;\r
}\r
* Constructor.\r
*/\r
ReDirEntryFilter_t::ReDirEntryFilter_t() :\r
- m_types(ReDirStatus_t::TC_ALL),\r
- m_nodePatterns(NULL),\r
- m_pathPatterns(NULL),\r
- m_minSize(0),\r
- m_maxSize(-1),\r
- //m_minAge(0),\r
- //m_maxAge(0),\r
- m_minDepth(0),\r
- m_maxDepth(512)\r
-{\r
+ m_types(ReDirStatus_t::TC_ALL),\r
+ m_nodePatterns(NULL),\r
+ m_pathPatterns(NULL),\r
+ m_minSize(0),\r
+ m_maxSize(-1),\r
+ //m_minAge(0),\r
+ //m_maxAge(0),\r
+ m_minDepth(0),\r
+ m_maxDepth(512) {\r
setFiletimeUndef(m_minAge);\r
setFiletimeUndef(m_maxAge);\r
}\r
/**\r
* Destructor.\r
*/\r
-ReDirEntryFilter_t::~ReDirEntryFilter_t(){\r
+ReDirEntryFilter_t::~ReDirEntryFilter_t() {\r
}\r
/**\r
*\r
*/\r
-bool ReDirEntryFilter_t::match(ReDirStatus_t& entry){\r
+bool ReDirEntryFilter_t::match(ReDirStatus_t& entry) {\r
bool rc = false;\r
do {\r
if (0 == (entry.type() & m_types))\r
break;\r
- int64_t size = entry.fileSize();\r
- if (m_minSize > 0 && size < m_minSize)\r
+ int64_t size = entry.fileSize();\r
+ if (m_minSize > 0 && size < m_minSize)\r
break;\r
if (m_maxSize >= 0 && size > m_maxSize)\r
break;\r
- if (! filetimeIsUndefined(m_minAge) && *entry.modified() > m_minAge)\r
+ if (!filetimeIsUndefined(m_minAge) && *entry.modified() > m_minAge)\r
break;\r
- if (! filetimeIsUndefined(m_maxAge) && m_maxAge > *entry.modified())\r
+ if (!filetimeIsUndefined(m_maxAge) && m_maxAge > *entry.modified())\r
break;\r
const char* node = entry.node();\r
- if (m_nodePatterns != NULL && ! m_nodePatterns->match(node))\r
+ if (m_nodePatterns != NULL && !m_nodePatterns->match(node))\r
break;\r
rc = true;\r
- } while(false);\r
+ } while (false);\r
return rc;\r
-};\r
+}\r
+;\r
\r
#ifdef __linux__\r
/**\r
* @return the status of the current file\r
*/\r
struct stat* ReDirStatus_t::getStatus() {\r
- if (m_status.st_ino == 0){\r
+ if (m_status.st_ino == 0) {\r
if (stat(fullName(), &m_status) != 0)\r
- m_status.st_ino = 0;\r
+ m_status.st_ino = 0;\r
}\r
return &m_status;\r
}\r
* Constructor.\r
*/\r
ReDirTreeStatistic::ReDirTreeStatistic() :\r
- m_directories(0),\r
- m_files(0),\r
- m_sizes(0ll)\r
-{\r
+ m_directories(0),\r
+ m_files(0),\r
+ m_sizes(0ll) {\r
}\r
/**\r
* Builds a string describing the data.\r
* @param formatFiles the <code>sprintf</code> format for the directory count, e.g. "%6d"\r
* @return a human readable string\r
*/\r
-const char* ReDirTreeStatistic::statisticAsString(ReByteBuffer& buffer, bool append,\r
- const char* formatFiles, const char* formatSizes, const char* formatDirs)\r
-{\r
- if (! append)\r
+const char* ReDirTreeStatistic::statisticAsString(ReByteBuffer& buffer,\r
+ bool append, const char* formatFiles, const char* formatSizes,\r
+ const char* formatDirs) {\r
+ if (!append)\r
buffer.setLength(0);\r
buffer.appendInt(m_files, formatFiles);\r
buffer.append(i18n("file(s)")).appendChar(' ');\r
}\r
\r
/**\r
-* Constructor.\r
-*\r
-* @param triggerCount efficiency: only every N calls a time check takes place\r
-* @param interval the minimum number of seconds between two traces\r
-*/\r
+ * Constructor.\r
+ *\r
+ * @param triggerCount efficiency: only every N calls a time check takes place\r
+ * @param interval the minimum number of seconds between two traces\r
+ */\r
ReTraceUnit::ReTraceUnit(int triggerCount, int interval) :\r
- m_count(0),\r
- m_triggerCount(triggerCount),\r
- m_lastTrace(0),\r
- m_interval(interval),\r
- m_startTime(time(NULL))\r
-{\r
+ m_count(0),\r
+ m_triggerCount(triggerCount),\r
+ m_lastTrace(0),\r
+ m_interval(interval),\r
+ m_startTime(time(NULL)) {\r
m_lastTrace = m_startTime;\r
}\r
/**\r
* Destructor.\r
*/\r
-ReTraceUnit::~ReTraceUnit(){\r
+ReTraceUnit::~ReTraceUnit() {\r
}\r
\r
/**\r
* @param message message for the trace\r
* @return <code>true</code> (for chaining)\r
*/\r
-bool ReTraceUnit::trace(const char* message){\r
+bool ReTraceUnit::trace(const char* message) {\r
printf("%d\n", message);\r
return true;\r
}\r
*\r
* @param base the base directory. The traversal starts at this point\r
*/\r
-ReTraverser::ReTraverser(const char* base, ReTraceUnit* tracer, ReLogger* logger) :\r
- ReDirTreeStatistic(),\r
- m_minLevel(0),\r
- m_maxLevel(512),\r
- m_level(-1),\r
- m_base(base),\r
- // m_dirs\r
- m_passNoForDirSearch(2),\r
- m_dirPatterns(NULL),\r
- m_tracer(tracer),\r
- m_logger(logger)\r
-{\r
+ReTraverser::ReTraverser(const char* base, ReTraceUnit* tracer,\r
+ ReLogger* logger) :\r
+ ReDirTreeStatistic(),\r
+ m_minLevel(0),\r
+ m_maxLevel(512),\r
+ m_level(-1),\r
+ m_base(base),\r
+ // m_dirs\r
+ m_passNoForDirSearch(2),\r
+ m_dirPatterns(NULL),\r
+ m_tracer(tracer),\r
+ m_logger(logger) {\r
memset(m_dirs, 0, sizeof m_dirs);\r
m_dirs[0] = new ReDirStatus_t(m_logger);\r
// remove a preceeding "./". This simplifies the pattern expressions:\r
- if (m_base.startsWith(ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())){\r
+ if (m_base.startsWith(\r
+ ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())) {\r
m_base.remove(0, 2);\r
}\r
}\r
*\r
* @param base the base directory to search\r
*/\r
-void ReTraverser::changeBase(const char* base){\r
+void ReTraverser::changeBase(const char* base) {\r
destroy();\r
m_base.setLength(0).append(base);\r
memset(m_dirs, 0, sizeof m_dirs);\r
m_dirs[0] = new ReDirStatus_t(m_logger);\r
// remove a preceeding "./". This simplifies the pattern expressions:\r
- if (m_base.startsWith(ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())){\r
+ if (m_base.startsWith(\r
+ ReByteBuffer(".").appendChar(OS_SEPARATOR_CHAR).str())) {\r
m_base.remove(0, 2);\r
}\r
}\r
* Releases the resources.\r
*/\r
void ReTraverser::destroy() {\r
- for (size_t ix = 0; ix < sizeof m_dirs / sizeof m_dirs[0]; ix++){\r
- if (m_dirs[ix] != NULL){\r
+ for (size_t ix = 0; ix < sizeof m_dirs / sizeof m_dirs[0]; ix++) {\r
+ if (m_dirs[ix] != NULL) {\r
m_dirs[ix]->freeEntry();\r
delete m_dirs[ix];\r
m_dirs[ix] = NULL;\r
* otherwise: the stack entry with the next file in the\r
* directory tree. May be a directory too\r
*/\r
-ReDirStatus_t* ReTraverser::rawNextFile(int& level)\r
-{\r
+ReDirStatus_t* ReTraverser::rawNextFile(int& level) {\r
ReDirStatus_t* rc = NULL;\r
bool alreadyRead = false;\r
bool again;\r
- do{\r
- again = false;\r
- if (m_level < 0){\r
+ do {\r
+ again = false;\r
+ if (m_level < 0) {\r
// Not yet initialized?\r
if (m_dirs[0]->m_passNo == 2)\r
rc = NULL;\r
else {\r
// first call:\r
- if (initEntry(m_base.str(), NULL, 0)){\r
+ if (initEntry(m_base.str(), NULL, 0)) {\r
m_directories++;\r
if (1 != m_passNoForDirSearch)\r
- rc = m_dirs[0];\r
+ rc = m_dirs[0];\r
else\r
again = alreadyRead = true;\r
}\r
}\r
} else {\r
ReDirStatus_t* current = m_dirs[m_level];\r
- if (alreadyRead || current->findNext()){\r
+ if (alreadyRead || current->findNext()) {\r
alreadyRead = false;\r
// a file or directory found:\r
- if (m_tracer != NULL && m_tracer->isCountTriggered() \r
- && m_tracer->isTimeTriggered())\r
+ if (m_tracer != NULL && m_tracer->isCountTriggered()\r
+ && m_tracer->isTimeTriggered())\r
m_tracer->trace(current->fullName());\r
- if (current->m_passNo != m_passNoForDirSearch){\r
+ if (current->m_passNo != m_passNoForDirSearch) {\r
// we search for any file:\r
rc = m_dirs[m_level];\r
} else {\r
// we are interested only in true subdirectories:\r
again = true;\r
- if (m_level < m_maxLevel && current->isDirectory()\r
- && ! current->isDotDir() && ! current->isLink()\r
- && (m_dirPatterns == NULL \r
- || isAllowedDir(current->node()))){\r
+ if (m_level < m_maxLevel && current->isDirectory()\r
+ && !current->isDotDir() && !current->isLink()\r
+ && (m_dirPatterns == NULL\r
+ || isAllowedDir(current->node()))) {\r
// open a new level\r
- alreadyRead = initEntry(current->m_path, current->node() , m_level + 1);\r
+ alreadyRead = initEntry(current->m_path,\r
+ current->node(), m_level + 1);\r
m_directories++;\r
}\r
}\r
} else {\r
// the current subdir does not have more files:\r
- if (current->m_passNo == 1){\r
+ if (current->m_passNo == 1) {\r
// we start the second pass:\r
alreadyRead = initEntry(current->m_path, NULL, -1);\r
current->m_passNo = 2;\r
} else {\r
// this subdirectory is complete. We continue in the parent directory:\r
current->freeEntry();\r
- if ( --m_level >= 0){\r
+ if (--m_level >= 0) {\r
again = true;\r
}\r
}\r
}\r
if (rc != NULL && rc->isDotDir())\r
again = true;\r
- } while(again);\r
- if (rc != NULL && ! rc->isDirectory()){\r
+ } while (again);\r
+ if (rc != NULL && !rc->isDirectory()) {\r
m_files++;\r
if (m_sizes >= 0)\r
m_sizes += rc->fileSize();\r
* otherwise: the info about the next file in the\r
* directory tree\r
*/\r
-ReDirStatus_t* ReTraverser::nextFile(int& level, ReDirEntryFilter_t* filter){\r
+ReDirStatus_t* ReTraverser::nextFile(int& level, ReDirEntryFilter_t* filter) {\r
ReDirStatus_t* rc = rawNextFile(level);\r
- while (rc != NULL){\r
- if (filter == NULL || filter->match(*rc)){\r
+ while (rc != NULL) {\r
+ if (filter == NULL || filter->match(*rc)) {\r
break;\r
}\r
rc = rawNextFile(level);\r
* @return <code>true</code>: a new file is available<br>\r
* <cude>false/code>: findFirstEntry() signals: no entry.\r
*/\r
-bool ReTraverser::initEntry(const ReByteBuffer& parent, const char* node, int level){\r
- bool rc = false;\r
- if (level < MAX_ENTRY_STACK_DEPTH){\r
- if (level >= 0)\r
- m_level = level;\r
+bool ReTraverser::initEntry(const ReByteBuffer& parent, const char* node,\r
+ int level) {\r
+ bool rc = false;\r
+ if (level < MAX_ENTRY_STACK_DEPTH) {\r
+ if (level >= 0)\r
+ m_level = level;\r
if (m_dirs[m_level] == NULL)\r
m_dirs[m_level] = new ReDirStatus_t(m_logger);\r
ReDirStatus_t* current = m_dirs[m_level];\r
- current->m_passNo = 1;\r
- if (level >= 0){\r
- current->m_path.set(parent.str(), parent.length());\r
- if (! parent.endsWith(OS_SEPARATOR))\r
- current->m_path.append(OS_SEPARATOR);\r
- if (node != NULL)\r
- current->m_path.append(node).append(OS_SEPARATOR);\r
- }\r
- rc = current->findFirst();\r
+ current->m_passNo = 1;\r
+ if (level >= 0) {\r
+ current->m_path.set(parent.str(), parent.length());\r
+ if (!parent.endsWith(OS_SEPARATOR))\r
+ current->m_path.append(OS_SEPARATOR);\r
+ if (node != NULL)\r
+ current->m_path.append(node).append(OS_SEPARATOR);\r
+ }\r
+ rc = current->findFirst();\r
}\r
- return rc;\r
+ return rc;\r
}\r
\r
/**\r
*\r
* @param filter the filter with the properties to set\r
*/\r
-void ReTraverser::setPropertiesFromFilter(ReDirEntryFilter_t* filter){\r
+void ReTraverser::setPropertiesFromFilter(ReDirEntryFilter_t* filter) {\r
m_minLevel = filter->m_minDepth;\r
m_maxLevel = filter->m_maxDepth;\r
setDirPattern(filter->m_pathPatterns);\r
* @return NULL: not available<br>\r
* otherwise: the wanted entry\r
*/\r
-ReDirStatus_t* ReTraverser::topOfStack(int offsetFromTop){\r
+ReDirStatus_t* ReTraverser::topOfStack(int offsetFromTop) {\r
ReDirStatus_t* rc = NULL;\r
if (offsetFromTop >= 0 && m_level - 1 - offsetFromTop >= 0)\r
rc = m_dirs[m_level - 1 - offsetFromTop];\r
* @param time the filetime to test
* @return <code>true</code>: 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__
/** 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;
bool m_getPrivilege;
#endif
};
-class ReDirEntryFilter_t{
+class ReDirEntryFilter_t {
public:
ReDirEntryFilter_t();
~ReDirEntryFilter_t();
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();
* 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 <code>true</code>: the counter has reached <code>m_triggerCount</code>
- */
- inline bool isCountTriggered(){
+ */
+ inline bool isCountTriggered() {
bool rc = ++m_count % m_triggerCount == 0;
return rc;
}
* @return <code>true</code>: the last trace has been done after
* at least <code>m_interval</code> 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;
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;
}
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);
}
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
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 <code>true</code>: the subdir will be processed<br>
- * <code>false</code>: 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 <code>true</code>: the subdir will be processed<br>
+ * <code>false</code>: 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];
* @param time2 second operand
* @return <code>true</code>: 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"
* Constructor.
*/
ReMatcher::ReMatcher() :
- m_findAll(false),
- m_ignoreCase(true),
- m_notPattern(false)
-{
+ m_findAll(false),
+ m_ignoreCase(true),
+ m_notPattern(false) {
}
/**
* 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() {
}
/**
* @return <code>true</code>: success<br>
* <code>false</code>: 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, '*');
* @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());
}
/**
* m_notPattern: the name matches not<br>
* <code>false</code>: 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;
}
* <code>false</code>: 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);
}
* m_notPattern: the name matches not<br>
* <code>false</code>: 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;
}
/**
* @param prefix NULL or a prefix of the output
* @return <code>buffer.str()</code> (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: ");
* 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;
}
* @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);
}
* <code>false</code>: 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;
}
* 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;
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;
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;
}
* 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;
}
/**
* @param prefix NULL or a prefix of the output
* @return <code>buffer.str()</code> (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);
}
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;
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 <code>true</code>: 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;
/** @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);
* @param name the string to Test
* @return <code>true</code>: 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 <code>true</code>: 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: