code format

This commit is contained in:
2022-12-14 14:13:52 +03:00
parent 430a41fefc
commit c2b8a8d6da
297 changed files with 27331 additions and 24162 deletions

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
CSS colors
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
CSS colors
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "colors_p.h"

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Color collection
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Color collection
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef colors_p_H
@@ -26,8 +26,9 @@
class PIColorCollection {
public:
static PIColorCollection & instance();
PIVariantTypes::Color getCSSColor(const PIString & name) const {return css_color.value(name);}
PIString getCSSName(const PIVariantTypes::Color color) const {return css_name.value(color);}
PIVariantTypes::Color getCSSColor(const PIString & name) const { return css_color.value(name); }
PIString getCSSName(const PIVariantTypes::Color color) const { return css_name.value(color); }
private:
PIColorCollection();
PIMap<PIString, PIVariantTypes::Color> css_color;

View File

@@ -1,27 +1,28 @@
/*
PIP - Platform Independent Primitives
Bit array
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Bit array
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pibitarray.h"
#include "picout.h"
PICout operator <<(PICout s, const PIBitArray & ba) {
PICout operator<<(PICout s, const PIBitArray & ba) {
s.space();
s.saveAndSetControls(0);
for (uint i = 0; i < ba.bitSize(); ++i) {
@@ -33,7 +34,7 @@ PICout operator <<(PICout s, const PIBitArray & ba) {
}
#ifdef PIP_STD_IOSTREAM
std::ostream &operator <<(std::ostream & s, const PIBitArray & ba) {
std::ostream & operator<<(std::ostream & s, const PIBitArray & ba) {
for (uint i = 0; i < ba.bitSize(); ++i) {
s << ba[i];
if (i % 8 == 7) s << ' ';
@@ -41,4 +42,3 @@ std::ostream &operator <<(std::ostream & s, const PIBitArray & ba) {
return s;
}
#endif

View File

@@ -2,24 +2,24 @@
* \~\brief
* \~english Bit array
* \~russian Битовый массив
*/
*/
/*
PIP - Platform Independent Primitives
Bit array
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Bit array
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIBITARRAY_H
@@ -33,74 +33,109 @@
//! \~english The %PIBitArray class provides an space-efficient array of bits.
//! \~russian Класс %PIBitArray представляет собой компактный массив битов.
class PIP_EXPORT PIBitArray {
template <typename P>
friend PIBinaryStream<P> & operator >>(PIBinaryStream<P> & s, PIBitArray & v);
template <typename P>
friend PIBinaryStream<P> & operator <<(PIBinaryStream<P> & s, const PIBitArray & v);
public:
template<typename P>
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIBitArray & v);
template<typename P>
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIBitArray & v);
public:
//! \~english Constructs bit array with "size" size.
//! \~russian Создает битовый массив с размером "size".
PIBitArray(const int & size = 0) {resize(size);}
PIBitArray(const int & size = 0) { resize(size); }
//! \~english Constructs bit array with size 8 and values from "val".
//! \~russian Создает битовый массив с размером 8 и значениями из "val".
PIBitArray(uchar val) {resize(sizeof(val) * 8); data_[0] = val;}
PIBitArray(uchar val) {
resize(sizeof(val) * 8);
data_[0] = val;
}
//! \~english Constructs bit array with size 16 and values from "val".
//! \~russian Создает битовый массив с размером 16 и значениями из "val".
PIBitArray(ushort val) {resize(sizeof(val) * 8); memcpy(data(), &val, sizeof(val));}
PIBitArray(ushort val) {
resize(sizeof(val) * 8);
memcpy(data(), &val, sizeof(val));
}
//! \~english Constructs bit array with size 32 and values from "val".
//! \~russian Создает битовый массив с размером 32 и значениями из "val".
PIBitArray(uint val) {resize(sizeof(val) * 8); memcpy(data(), &val, sizeof(val));}
PIBitArray(uint val) {
resize(sizeof(val) * 8);
memcpy(data(), &val, sizeof(val));
}
//! \~english Constructs bit array with size 64 and values from "val".
//! \~russian Создает битовый массив с размером 64 и значениями из "val".
PIBitArray(ullong val) {resize(sizeof(val) * 8); memcpy(data(), &val, sizeof(val));}
PIBitArray(ullong val) {
resize(sizeof(val) * 8);
memcpy(data(), &val, sizeof(val));
}
//! \~english Constructs bit array with size "bytes * 8" and values from "data".
//! \~russian Создает битовый массив с размером "bytes * 8" и значениями из "data".
PIBitArray(const uchar * data, uint bytes) {resize(bytes * 8); memcpy(this->data(), data, bytes);}
PIBitArray(const uchar * data, uint bytes) {
resize(bytes * 8);
memcpy(this->data(), data, bytes);
}
//! \~english Returns a size in bits.
//! \~russian Возвращает размер в битах.
uint bitSize() const {return size_;}
uint bitSize() const { return size_; }
//! \~english Returns a size in bytes.
//! \~russian Возвращает размер в байтах.
uint byteSize() const {return bytesInBits(size_);}
uint byteSize() const { return bytesInBits(size_); }
//! \~english Resize this array to "size" bits.
//! \~russian Изменяет размер массива до "size" битов.
PIBitArray & resize(const uint & size) {size_ = size; data_.resize(bytesInBits(size_)); return *this;}
PIBitArray & resize(const uint & size) {
size_ = size;
data_.resize(bytesInBits(size_));
return *this;
}
//! \~english Set bit with index "index" to 0.
//! \~russian Устанавливает бит с индексом "index" в 0.
PIBitArray & clearBit(const uint & index) {data_[index / 8] &= ~(1 << (index % 8)); return *this;}
PIBitArray & clearBit(const uint & index) {
data_[index / 8] &= ~(1 << (index % 8));
return *this;
}
//! \~english Set bit with index "index" to 1.
//! \~russian Устанавливает бит с индексом "index" в 1.
PIBitArray & setBit(const uint & index) {data_[index / 8] |= (1 << (index % 8)); return *this;}
PIBitArray & setBit(const uint & index) {
data_[index / 8] |= (1 << (index % 8));
return *this;
}
//! \~english Set bit with index "index" to "value".
//! \~russian Устанавливает бит с индексом "index" в "value".
PIBitArray & writeBit(const uint & index, const bool & value) {if (value) setBit(index); else clearBit(index); return *this;}
PIBitArray & writeBit(const uint & index, const bool & value) {
if (value)
setBit(index);
else
clearBit(index);
return *this;
}
//! \~english Set bit with index "index" to "value".
//! \~russian Устанавливает бит с индексом "index" в "value".
PIBitArray & writeBit(const uint & index, const uchar & value) {return writeBit(index, value > 0);}
PIBitArray & writeBit(const uint & index, const uchar & value) { return writeBit(index, value > 0); }
//! \~english Add bit with value "value" to the end of array.
//! \~russian Добавляет бит со значением "value" в конец массива.
PIBitArray & push_back(const bool & value) {resize(size_ + 1); writeBit(size_ - 1, value); return *this;}
PIBitArray & push_back(const bool & value) {
resize(size_ + 1);
writeBit(size_ - 1, value);
return *this;
}
//! \~english Add bit with value "value" to the end of array.
//! \~russian Добавляет бит со значением "value" в конец массива.
PIBitArray & push_back(const uchar & value) {return push_back(value > 0);}
PIBitArray & push_back(const uchar & value) { return push_back(value > 0); }
//! \~english Insert bit with value "value" after "index" position.
//! \~russian Вставляет бит со значением "value" после положения "index".
@@ -110,29 +145,35 @@ public:
uchar c = data_[si];
for (uint i = fi; i > si; --i) {
data_[i] <<= 1;
if ((0x80 & data_[i - 1]) == 0x80) data_[i] |= 1;
else data_[i] &= 0xFE;}
if ((0x80 & data_[i - 1]) == 0x80)
data_[i] |= 1;
else
data_[i] &= 0xFE;
}
data_[si] &= (0xFF >> (7 - ti));
data_[si] |= ((c << 1) & (0xFF << (ti)));
if (value) data_[si] |= (1 << ti);
else data_[si] &= ~(1 << ti);
return *this;}
if (value)
data_[si] |= (1 << ti);
else
data_[si] &= ~(1 << ti);
return *this;
}
//! \~english Insert bit with value "value" after "index" position.
//! \~russian Вставляет бит со значением "value" после положения "index".
PIBitArray & insert(const uint & index, const uchar & value) {return insert(index, value > 0);}
PIBitArray & insert(const uint & index, const uchar & value) { return insert(index, value > 0); }
//! \~english Add bit with value "value" to the beginning of array.
//! \~russian Добавляет бит со значением "value" в начало массива.
PIBitArray & push_front(const bool & value) {return insert(0, value);}
PIBitArray & push_front(const bool & value) { return insert(0, value); }
//! \~english Add bit with value "value" to the beginning of array.
//! \~russian Добавляет бит со значением "value" в начало массива.
PIBitArray & push_front(const uchar & value) {return push_front(value > 0);}
PIBitArray & push_front(const uchar & value) { return push_front(value > 0); }
//! \~english Remove one bit from the end of array.
//! \~russian Удаляет один бит с конца массива.
PIBitArray & pop_back() {return resize(size_ - 1);}
PIBitArray & pop_back() { return resize(size_ - 1); }
//! \~english Remove one bit from the beginning of array.
//! \~russian Удаляет один бит с начала массива.
@@ -141,89 +182,128 @@ public:
uint fi = byteSize() - 1;
for (uint i = 0; i < fi; ++i) {
data_[i] >>= 1;
if ((1 & data_[i + 1]) == 1) data_[i] |= 0x80;
else data_[i] &= 0x7F;}
if ((1 & data_[i + 1]) == 1)
data_[i] |= 0x80;
else
data_[i] &= 0x7F;
}
data_[fi] >>= 1;
resize(size_ - 1);
return *this;}
return *this;
}
//! \~english Add bits "ba" to the end of array.
//! \~russian Добавляет биты "ba" в конец массива.
PIBitArray & append(const PIBitArray & ba) {for (uint i = 0; i < ba.bitSize(); ++i) push_back(ba[i]); return *this;}
PIBitArray & append(const PIBitArray & ba) {
for (uint i = 0; i < ba.bitSize(); ++i)
push_back(ba[i]);
return *this;
}
//! \~english Returns pointer to bytes data of array.
//! \~russian Возвращает указатель на байтовое содержимое массива.
uchar * data() {return data_.data();}
uchar * data() { return data_.data(); }
//! \~english Returns data of array as \b uchar.
//! \~russian Возвращает байтовое содержимое массива как \b uchar.
uchar toUChar() {if (size_ == 0) return 0; return data_[0];}
uchar toUChar() {
if (size_ == 0) return 0;
return data_[0];
}
//! \~english Returns data of array as \b ushort.
//! \~russian Возвращает байтовое содержимое массива как \b ushort.
ushort toUShort() {ushort t = 0; memcpy(&t, data(), piMin<uint>(byteSize(), sizeof(t))); return t;}
ushort toUShort() {
ushort t = 0;
memcpy(&t, data(), piMin<uint>(byteSize(), sizeof(t)));
return t;
}
//! \~english Returns data of array as \b uint.
//! \~russian Возвращает байтовое содержимое массива как \b uint.
uint toUInt() {uint t = 0; memcpy(&t, data(), piMin<uint>(byteSize(), sizeof(t))); return t;}
uint toUInt() {
uint t = 0;
memcpy(&t, data(), piMin<uint>(byteSize(), sizeof(t)));
return t;
}
//! \~english Returns data of array as \b ullong.
//! \~russian Возвращает байтовое содержимое массива как \b ullong.
ullong toULLong() {ullong t = 0; memcpy(&t, data(), piMin<uint>(byteSize(), sizeof(t))); return t;}
ullong toULLong() {
ullong t = 0;
memcpy(&t, data(), piMin<uint>(byteSize(), sizeof(t)));
return t;
}
//! \~english Returns bit value at index "index".
//! \~russian Возвращает значение бита с индексом "index".
bool at(const uint & index) const {return (1 & (data_[index / 8] >> (index % 8))) == 1 ? true : false;}
bool at(const uint & index) const { return (1 & (data_[index / 8] >> (index % 8))) == 1 ? true : false; }
//! \~english Returns bit value at index "index".
//! \~russian Возвращает значение бита с индексом "index".
bool operator [](const uint & index) const {return at(index);}
bool operator[](const uint & index) const { return at(index); }
//! \~english Similar to \a append().
//! \~russian Аналог \a append().
void operator +=(const PIBitArray & ba) {append(ba);}
void operator+=(const PIBitArray & ba) { append(ba); }
//! \~english Returns if two bit arrays are similar.
//! \~russian Возвращает равны ли для битовых массива.
bool operator ==(const PIBitArray & ba) const {if (bitSize() != ba.bitSize()) return false; for (uint i = 0; i < bitSize(); ++i) if (at(i) != ba[i]) return false; return true;}
bool operator==(const PIBitArray & ba) const {
if (bitSize() != ba.bitSize()) return false;
for (uint i = 0; i < bitSize(); ++i)
if (at(i) != ba[i]) return false;
return true;
}
//! \~english Returns if two bit arrays are not similar.
//! \~russian Возвращает не равны ли для битовых массива.
bool operator !=(const PIBitArray & ba) const {return !(*this == ba);}
bool operator!=(const PIBitArray & ba) const { return !(*this == ba); }
//! \~english Resize and set values from "val".
//! \~russian Изменяет размер и устанавливает значения из "val".
void operator =(const uchar & val) {resize(sizeof(val) * 8); data_[0] = val;}
void operator=(const uchar & val) {
resize(sizeof(val) * 8);
data_[0] = val;
}
//! \~english Resize and set values from "val".
//! \~russian Изменяет размер и устанавливает значения из "val".
void operator =(const ushort & val) {resize(sizeof(val) * 8); memcpy(data(), &val, sizeof(val));}
void operator=(const ushort & val) {
resize(sizeof(val) * 8);
memcpy(data(), &val, sizeof(val));
}
//! \~english Resize and set values from "val".
//! \~russian Изменяет размер и устанавливает значения из "val".
void operator =(const uint & val) {resize(sizeof(val) * 8); memcpy(data(), &val, sizeof(val));}
void operator=(const uint & val) {
resize(sizeof(val) * 8);
memcpy(data(), &val, sizeof(val));
}
//! \~english Resize and set values from "val".
//! \~russian Изменяет размер и устанавливает значения из "val".
void operator =(const ullong & val) {resize(sizeof(val) * 8); memcpy(data(), &val, sizeof(val));}
void operator=(const ullong & val) {
resize(sizeof(val) * 8);
memcpy(data(), &val, sizeof(val));
}
private:
static uint bytesInBits(const uint & bits) {return (bits + 7) / 8;}
static uint bytesInBits(const uint & bits) { return (bits + 7) / 8; }
PIVector<uchar> data_;
uint size_;
};
#ifdef PIP_STD_IOSTREAM
//std::ostream & operator <<(std::ostream & s, const PIBitArray & ba);
// std::ostream & operator <<(std::ostream & s, const PIBitArray & ba);
#endif
//! \relatesalso PIByteArray
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
PICout operator <<(PICout s, const PIBitArray & ba);
PICout operator<<(PICout s, const PIBitArray & ba);
#endif // PIBITARRAY_H

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Byte array
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Byte array
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pibytearray.h"
@@ -74,9 +74,9 @@
static const uchar base64Table[64] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,
0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f};
0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,
0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f};
static const uchar base64InvTable[256] = {
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,

View File

@@ -3,31 +3,32 @@
* \~\brief
* \~english Byte array
* \~russian Байтовый массив
*/
*/
/*
PIP - Platform Independent Primitives
Byte array
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Byte array
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIBYTEARRAY_H
#define PIBYTEARRAY_H
#include "pichar.h"
#include "pibinarystream.h"
#include "pichar.h"
#include <stdio.h>
class PIString;
@@ -38,8 +39,7 @@ class PIByteArray;
//! \~\brief
//! \~english The %PIByteArray class provides an array of bytes.
//! \~russian Класс %PIByteArray представляет собой массив байтов.
class PIP_EXPORT PIByteArray: public PIBinaryStream<PIByteArray>
{
class PIP_EXPORT PIByteArray: public PIBinaryStream<PIByteArray> {
public:
typedef ::PIMemoryBlock RawData DEPRECATEDM("use PIMemoryBlock instead");
@@ -59,11 +59,11 @@ public:
//! \~english Constructs 0-filled byte array with size "size"
//! \~russian Создает заполненный "0" байтовый массив размером "size"
PIByteArray(const uint size) {resize(size);}
PIByteArray(const uint size) { resize(size); }
//! \~english Constructs byte array from data "data" and size "size"
//! \~russian Создает байтовый массив из данных по указателю "data" размером "size"
PIByteArray(const void * data, const uint size): d((const uchar*)data, size_t(size)) {}
PIByteArray(const void * data, const uint size): d((const uchar *)data, size_t(size)) {}
//! \~english Constructs byte array with size "size" filled by "t"
//! \~russian Создает заполненный "t" байтовый массив размером "size"
@@ -78,16 +78,14 @@ public:
//! PIByteArray v{1,2,3};
//! piCout << v; // {1, 2, 3}
//! \endcode
PIByteArray(std::initializer_list<uchar> init_list) : d(init_list) {}
PIByteArray(std::initializer_list<uchar> init_list): d(init_list) {}
//! \~english Swaps array `v` other with this array.
//! \~russian Меняет местами массив `v` с этим массивом.
//! \~\details
//! \~english This operation is very fast and never fails.
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
inline void swap(PIByteArray & other) {
d.swap(other.d);
}
inline void swap(PIByteArray & other) { d.swap(other.d); }
//! \~english Iterator to the first element.
//! \~russian Итератор на первый элемент.
@@ -97,7 +95,7 @@ public:
//! \~russian Если массив - пуст, возвращаемый итератор будет равен \a end().
//! \~\return \ref stl_iterators
//! \~\sa \a end(), \a rbegin(), \a rend()
inline PIDeque<uchar>::iterator begin() {return d.begin();}
inline PIDeque<uchar>::iterator begin() { return d.begin(); }
//! \~english Iterator to the element following the last element.
//! \~russian Итератор на элемент, следующий за последним элементом.
@@ -109,10 +107,10 @@ public:
//! попытка доступа к нему приведёт к выходу за разрешенную память.
//! \~\return \ref stl_iterators
//! \~\sa \a begin(), \a rbegin(), \a rend()
inline PIDeque<uchar>::iterator end() {return d.end();}
inline PIDeque<uchar>::iterator end() { return d.end(); }
inline PIDeque<uchar>::const_iterator begin() const {return d.begin();}
inline PIDeque<uchar>::const_iterator end() const {return d.end();}
inline PIDeque<uchar>::const_iterator begin() const { return d.begin(); }
inline PIDeque<uchar>::const_iterator end() const { return d.end(); }
//! \~english Returns a reverse iterator to the first element of the reversed array.
//! \~russian Обратный итератор на первый элемент.
@@ -125,7 +123,7 @@ public:
//! Если массив пустой, то совпадает с итератором \a rend().
//! \~\return \ref stl_iterators
//! \~\sa \a rend(), \a begin(), \a end()
inline PIDeque<uchar>::reverse_iterator rbegin() {return d.rbegin();}
inline PIDeque<uchar>::reverse_iterator rbegin() { return d.rbegin(); }
//! \~english Returns a reverse iterator to the element.
//! following the last element of the reversed array.
@@ -140,25 +138,25 @@ public:
//! попытка доступа к нему приведёт к выходу за разрешенную память.
//! \~\return \ref stl_iterators
//! \~\sa \a rbegin(), \a begin(), \a end()
inline PIDeque<uchar>::reverse_iterator rend() {return d.rend();}
inline PIDeque<uchar>::reverse_iterator rend() { return d.rend(); }
inline PIDeque<uchar>::const_reverse_iterator rbegin() const {return d.rbegin();}
inline PIDeque<uchar>::const_reverse_iterator rend() const {return d.rend();}
inline PIDeque<uchar>::const_reverse_iterator rbegin() const { return d.rbegin(); }
inline PIDeque<uchar>::const_reverse_iterator rend() const { return d.rend(); }
//! \~english Number of elements in the container.
//! \~russian Количество элементов массива.
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
inline size_t size() const {return d.size();}
inline size_t size() const { return d.size(); }
//! \~english Number of elements in the container as signed value.
//! \~russian Количество элементов массива в виде знакового числа.
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
inline ssize_t size_s() const {return d.size_s();}
inline ssize_t size_s() const { return d.size_s(); }
//! \~english Same as \a size().
//! \~russian Синоним \a size().
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
inline size_t length() const {return d.length();}
inline size_t length() const { return d.length(); }
//! \~english Number of elements that the container has currently allocated space for.
//! \~russian Количество элементов, для которого сейчас выделена память массивом.
@@ -166,7 +164,7 @@ public:
//! \~english To find out the actual number of items, use the function \a size().
//! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size().
//! \~\sa \a reserve(), \a size(), \a size_s()
inline size_t capacity() const {return d.capacity();}
inline size_t capacity() const { return d.capacity(); }
//! \~english Checks if the container has no elements.
//! \~russian Проверяет пуст ли массив.
@@ -174,7 +172,7 @@ public:
//! \~english **true** if the container is empty, **false** otherwise
//! \~russian **true** если массив пуст, **false** иначе.
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
inline bool isEmpty() const {return d.isEmpty();}
inline bool isEmpty() const { return d.isEmpty(); }
//! \~english Checks if the container has elements.
//! \~russian Проверяет не пуст ли массив.
@@ -182,7 +180,7 @@ public:
//! \~english **true** if the container is not empty, **false** otherwise
//! \~russian **true** если массив не пуст, **false** иначе.
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
inline bool isNotEmpty() const {return d.isNotEmpty();}
inline bool isNotEmpty() const { return d.isNotEmpty(); }
//! \~english Tests whether at least one element in the array
//! passes the test implemented by the provided function `test`.
@@ -197,9 +195,7 @@ public:
//! Метод возвращает **false** при любом условии для пустого массива.
//! \~\details
//! \~\sa \a every(), \a contains(), \a entries(), \a forEach()
inline bool any(std::function<bool(uchar e)> test) const {
return d.any(test);
}
inline bool any(std::function<bool(uchar e)> test) const { return d.any(test); }
//! \~english Tests whether all elements in the array passes the test
//! implemented by the provided function `test`.
@@ -214,9 +210,7 @@ public:
//! Метод возвращает **true** при любом условии для пустого массива.
//! \~\details
//! \~\sa \a any(), \a contains(), \a entries(), \a forEach()
inline bool every(std::function<bool(uchar e)> test) const {
return d.every(test);
}
inline bool every(std::function<bool(uchar e)> test) const { return d.every(test); }
//! \~english Full access to element by `index`.
//! \~russian Полный доступ к элементу по индексу `index`.
@@ -228,8 +222,8 @@ public:
//! Индекс элемента должен лежать в пределах от `0` до `size()-1`.
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
//! \~\sa \a at()
inline uchar & operator [](size_t index) {return d[index];}
inline uchar operator [](size_t index) const {return d[index];}
inline uchar & operator[](size_t index) { return d[index]; }
inline uchar operator[](size_t index) const { return d[index]; }
//! \~english Read only access to element by `index`.
//! \~russian Доступ исключительно на чтение к элементу по индексу `index`.
@@ -240,7 +234,7 @@ public:
//! \~russian Индекс элемента считается от `0`.
//! Индекс элемента должен лежать в пределах от `0` до `size()-1`.
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
inline uchar at(size_t index) const {return d.at(index);}
inline uchar at(size_t index) const { return d.at(index); }
//! \~english Last element.
//! \~russian Последний элемент массива.
@@ -251,8 +245,8 @@ public:
//! \~russian Возвращает ссылку на последний элемент в массиве.
//! Эта функция предполагает, что массив не пустой.
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
inline uchar & back() {return d.back();}
inline uchar back() const {return d.back();}
inline uchar & back() { return d.back(); }
inline uchar back() const { return d.back(); }
//! \~english Last element.
//! \~russian Первый элемент массива.
@@ -263,8 +257,8 @@ public:
//! \~russian Возвращает ссылку на пенрвый элемент в массиве.
//! Эта функция предполагает, что массив не пустой.
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
inline uchar & front() {return d.front();}
inline uchar front() const {return d.front();}
inline uchar & front() { return d.front(); }
inline uchar front() const { return d.front(); }
//! \~english Tests if element `e` exists in the array.
//! \~russian Проверяет наличие элемента `e` в массиве.
@@ -298,9 +292,7 @@ public:
//! \~russian **true** если элемент `e` присутствует в массиве,
//! в остальных случаях **false**.
//! \~\sa \a every(), \a any(), \a entries()
inline bool contains(uchar e, ssize_t start = 0) const {
return d.contains(e, start);
}
inline bool contains(uchar e, ssize_t start = 0) const { return d.contains(e, start); }
//! \~english Count elements equal `e` in the array.
//! \~russian Подсчитывает количество элементов, совпадающих с элементом `e` в массиве.
@@ -321,9 +313,7 @@ public:
//! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу.
//! Значение по умолчанию равно 0, что означает, что просматривается весь массив.
//! \~\sa \a every(), \a any(), \a contains(), \a indexOf()
inline int entries(uchar e, ssize_t start = 0) const {
return d.entries(e, start);
}
inline int entries(uchar e, ssize_t start = 0) const { return d.entries(e, start); }
//! \~english Count elements in the array passes the test implemented by the provided function `test`.
//! \~russian Подсчитывает количество элементов в массиве,
@@ -347,9 +337,7 @@ public:
//! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу.
//! Значение по умолчанию равно 0, что означает, что просматривается весь массив.
//! \~\sa \a every(), \a any(), \a contains(), \a indexWhere()
inline int entries(std::function<bool(uchar e)> test, ssize_t start = 0) const {
return d.entries(test, start);
}
inline int entries(std::function<bool(uchar e)> test, ssize_t start = 0) const { return d.entries(test, start); }
//! \~english Returns the first index at which a given element `e`
//! can be found in the array, or `-1` if it is not present.
@@ -380,9 +368,7 @@ public:
//! piCout << v.indexOf(2, -3); // 0
//! \endcode
//! \~\sa \a indexWhere(), \a lastIndexOf(), \a lastIndexWhere(), \a contains()
inline ssize_t indexOf(const uchar & e, ssize_t start = 0) const {
return d.indexOf(e, start);
}
inline ssize_t indexOf(const uchar & e, ssize_t start = 0) const { return d.indexOf(e, start); }
//! \~english Returns the first index passes the test implemented by the provided function `test`,
//! or `-1` if it is not present.
@@ -412,9 +398,7 @@ public:
//! piCout << v.indexWhere([](const uchar & s){return s > 10;}); // -1
//! \endcode
//! \~\sa \a indexOf(), \a lastIndexOf(), \a lastIndexWhere(), \a contains()
inline ssize_t indexWhere(std::function<bool(const uchar & e)> test, ssize_t start = 0) const {
return d.indexWhere(test, start);
}
inline ssize_t indexWhere(std::function<bool(const uchar & e)> test, ssize_t start = 0) const { return d.indexWhere(test, start); }
//! \~english Returns the last index at which a given element `e`
//! can be found in the array, or `-1` if it is not present.
@@ -450,9 +434,7 @@ public:
//! piCout << v.lastIndexOf(2, 300); // 3
//! \endcode
//! \~\sa \a indexOf(), \a indexWhere(), \a lastIndexWhere(), \a contains()
inline ssize_t lastIndexOf(const uchar & e, ssize_t start = -1) const {
return d.lastIndexOf(e, start);
}
inline ssize_t lastIndexOf(const uchar & e, ssize_t start = -1) const { return d.lastIndexOf(e, start); }
//! \~english Returns the last index passes the test implemented by the provided function `test`,
//! or `-1` if it is not present.
@@ -490,7 +472,7 @@ public:
//! where is pointer. Default: start of array.
//! \~russian Опциональный аргумент `index` указывает на индекс c которого брать указатель.
//! По умолчанию указывает на начало массива.
inline uchar * data(size_t index = 0) {return d.data(index);}
inline uchar * data(size_t index = 0) { return d.data(index); }
//! \~english Read only pointer to array
//! \~russian Указатель на память массива только для чтения.
@@ -503,7 +485,7 @@ public:
//! Указатель остается действительным только до тех пор, пока массив не будет перераспределен.
//! Опциональный аргумент `index` указывает на индекс c которого брать указатель.
//! По умолчанию указывает на начало массива.
inline const uchar * data(size_t index = 0) const {return d.data(index);}
inline const uchar * data(size_t index = 0) const { return d.data(index); }
//! \~english Clear array, remove all elements.
//! \~russian Очищает массив, удаляет все элементы.
@@ -538,7 +520,7 @@ public:
//! \~english Same as \a fill().
//! \~russian Тоже самое что и \a fill().
//! \~\sa \a fill(), \a resize()
inline PIByteArray & assign(uchar e = 0) {return fill(e);}
inline PIByteArray & assign(uchar e = 0) { return fill(e); }
//! \~english First does `resize(new_size)` then `fill(e)`.
//! \~russian Сначала делает `resize(new_size)`, затем `fill(e)`.
@@ -655,9 +637,7 @@ public:
//! \~english Return sub-array starts from "index" and has "count" or less bytes
//! \~russian Возвращает подмассив с данными от индекса "index" и размером не более "count"
PIByteArray getRange(size_t index, size_t count) const {
return d.getRange(index, count);
}
PIByteArray getRange(size_t index, size_t count) const { return d.getRange(index, count); }
//! \~english Reverses this array.
//! \~russian Обращает порядок следования элементов этого массива.
@@ -784,7 +764,12 @@ public:
//! \~english Add to the end data "data" with size "size"
//! \~russian Добавляет в конец массива данные по указателю "data" размером "size"
PIByteArray & push_back(const void * data_, int size_) {uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this;}
PIByteArray & push_back(const void * data_, int size_) {
uint ps = size();
enlarge(size_);
memcpy(data(ps), data_, size_);
return *this;
}
//! \~english Appends the given element `e` to the begin of the array.
//! \~russian Добавляет элемент `e` в начало массива.
@@ -916,17 +901,13 @@ public:
//! \~russian Удаляет один элемент с начала массива и возвращает его.
//! \~\details
//! \~\sa \a take_front(), \a pop_back(), \a pop_front()
inline uchar take_back() {
return d.take_back();
}
inline uchar take_back() { return d.take_back(); }
//! \~english Remove one element from the begining of the array and return it.
//! \~russian Удаляет один элемент с конца массива и возвращает его.
//! \~\details
//! \~\sa \a take_front(), \a pop_back(), \a pop_front()
inline uchar take_front() {
return d.take_front();
}
inline uchar take_front() { return d.take_front(); }
//! \~english Returns a new array with all elements
//! that pass the test implemented by the provided function `test`.
@@ -939,9 +920,7 @@ public:
//! piCout << v2; // {3, 5, 7}
//! \endcode
//! \~\sa \a map(), \a any(), \a every()
inline PIByteArray filter(std::function<bool(const uchar & e)> test) const {
return PIByteArray(d.filter(test));
}
inline PIByteArray filter(std::function<bool(const uchar & e)> test) const { return PIByteArray(d.filter(test)); }
//! \~english Execute function `void f(const uchar & e)` for every element in array.
//! \~russian Выполняет функцию `void f(const uchar & e)` для каждого элемента массива.
@@ -957,9 +936,7 @@ public:
//! piCout << s; // 15
//! \endcode
//! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every()
inline void forEach(std::function<void(const uchar & e)> f) const {
d.forEach(f);
}
inline void forEach(std::function<void(const uchar & e)> f) const { d.forEach(f); }
//! \~english Execute function `void f(uchar & e)` for every element in array.
//! \~russian Выполняет функцию `void f(uchar & e)` для каждого элемента массива.
@@ -996,7 +973,7 @@ public:
//! piCout << sl; {"31", "A", "FF"}
//! \endcode
//! \~\sa \a forEach(), \a reduce()
template <typename ST>
template<typename ST>
inline PIDeque<ST> map(std::function<ST(const uchar & e)> f) const {
return d.map<ST>(f);
}
@@ -1042,7 +1019,7 @@ public:
//! piCout << s; // "12345"
//! \endcode
//! \~\sa \a forEach(), \a map()
template <typename ST>
template<typename ST>
inline ST reduce(std::function<ST(const uchar & e, const ST & acc)> f, const ST & initial = ST()) const {
return d.reduce<ST>(f, initial);
}
@@ -1061,8 +1038,16 @@ public:
PIByteArray & compressRLE(uchar threshold = 192);
PIByteArray & decompressRLE(uchar threshold = 192);
PIByteArray compressedRLE(uchar threshold = 192) {PIByteArray ba(*this); ba.compressRLE(threshold); return ba;}
PIByteArray decompressedRLE(uchar threshold = 192) {PIByteArray ba(*this); ba.decompressRLE(threshold); return ba;}
PIByteArray compressedRLE(uchar threshold = 192) {
PIByteArray ba(*this);
ba.compressRLE(threshold);
return ba;
}
PIByteArray decompressedRLE(uchar threshold = 192) {
PIByteArray ba(*this);
ba.decompressRLE(threshold);
return ba;
}
//! \~english Return string representation of data, each byte in "base" base, separated by spaces
//! \~russian Возвращает текстовое представление байтового массива, каждый байт в "base" системе, с пробелами
@@ -1078,15 +1063,28 @@ public:
//! \~english Add to the end data "data" with size "size"
//! \~russian Добавляет в конец массива данные по указателю "data" размером "size"
PIByteArray & append(const void * data_, int size_) {uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this;}
PIByteArray & append(const void * data_, int size_) {
uint ps = size();
enlarge(size_);
memcpy(data(ps), data_, size_);
return *this;
}
//! \~english Add to the end byte array "data"
//! \~russian Добавляет в конец массива содержимое массива "data"
PIByteArray & append(const PIByteArray & data_) {uint ps = size(); enlarge(data_.size_s()); memcpy(data(ps), data_.data(), data_.size()); return *this;}
PIByteArray & append(const PIByteArray & data_) {
uint ps = size();
enlarge(data_.size_s());
memcpy(data(ps), data_.data(), data_.size());
return *this;
}
//! \~english Add to the end "t"
//! \~russian Добавляет в конец массива байт "t"
PIByteArray & append(uchar t) {push_back(t); return *this;}
PIByteArray & append(uchar t) {
push_back(t);
return *this;
}
//! \~english Appends the given elements to the end of the array.
//! \~russian Добавляет элементы в конец массива.
@@ -1127,11 +1125,22 @@ public:
//! \~russian Возвращает хэш содержимого
uint hash() const;
void operator =(const PIDeque<uchar> & o) {resize(o.size()); memcpy(data(), o.data(), o.size());}
void operator=(const PIDeque<uchar> & o) {
resize(o.size());
memcpy(data(), o.data(), o.size());
}
PIByteArray & operator =(const PIByteArray & o) {if (this == &o) return *this; clear(); append(o); return *this;}
PIByteArray & operator=(const PIByteArray & o) {
if (this == &o) return *this;
clear();
append(o);
return *this;
}
PIByteArray & operator =(PIByteArray && o) {swap(o); return *this;}
PIByteArray & operator=(PIByteArray && o) {
swap(o);
return *this;
}
static PIByteArray fromUserInput(PIString str);
@@ -1155,17 +1164,16 @@ public:
return rs == s;
}
ssize_t binaryStreamSizeImp() const {return size();}
ssize_t binaryStreamSizeImp() const { return size(); }
private:
PIDeque<uchar> d;
};
//! \relatesalso PIByteArray
//! \~english Byte arrays compare operator
//! \~russian Оператор сравнения
inline bool operator <(const PIByteArray & v0, const PIByteArray & v1) {
inline bool operator<(const PIByteArray & v0, const PIByteArray & v1) {
if (v0.size() == v1.size()) {
if (v0.isEmpty()) return false;
return memcmp(v0.data(), v1.data(), v0.size()) < 0;
@@ -1176,7 +1184,7 @@ inline bool operator <(const PIByteArray & v0, const PIByteArray & v1) {
//! \relatesalso PIByteArray
//! \~english Byte arrays compare operator
//! \~russian Оператор сравнения
inline bool operator >(const PIByteArray & v0, const PIByteArray & v1) {
inline bool operator>(const PIByteArray & v0, const PIByteArray & v1) {
if (v0.size() == v1.size()) {
if (v0.isEmpty()) return false;
return memcmp(v0.data(), v1.data(), v0.size()) > 0;
@@ -1187,7 +1195,7 @@ inline bool operator >(const PIByteArray & v0, const PIByteArray & v1) {
//! \relatesalso PIByteArray
//! \~english Byte arrays compare operator
//! \~russian Оператор сравнения
inline bool operator ==(const PIByteArray & v0, const PIByteArray & v1) {
inline bool operator==(const PIByteArray & v0, const PIByteArray & v1) {
if (v0.size() == v1.size()) {
if (v0.isEmpty()) return true;
return memcmp(v0.data(), v1.data(), v0.size()) == 0;
@@ -1198,7 +1206,7 @@ inline bool operator ==(const PIByteArray & v0, const PIByteArray & v1) {
//! \relatesalso PIByteArray
//! \~english Byte arrays compare operator
//! \~russian Оператор сравнения
inline bool operator !=(const PIByteArray & v0, const PIByteArray & v1) {
inline bool operator!=(const PIByteArray & v0, const PIByteArray & v1) {
if (v0.size() == v1.size()) {
if (v0.isEmpty()) return false;
return memcmp(v0.data(), v1.data(), v0.size()) != 0;
@@ -1208,13 +1216,13 @@ inline bool operator !=(const PIByteArray & v0, const PIByteArray & v1) {
#ifdef PIP_STD_IOSTREAM
//! \relatesalso PIByteArray \brief Output to std::ostream operator
inline std::ostream & operator <<(std::ostream & s, const PIByteArray & ba);
inline std::ostream & operator<<(std::ostream & s, const PIByteArray & ba);
#endif
//! \relatesalso PIByteArray
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
PIP_EXPORT PICout operator <<(PICout s, const PIByteArray & ba);
PIP_EXPORT PICout operator<<(PICout s, const PIByteArray & ba);
//! \relatesalso PIBinaryStream
@@ -1239,18 +1247,25 @@ BINARY_STREAM_READ(PIByteArray) {
//! \relatesalso PIByteArray
//! \~english Returns PIByteArray::hash() of "ba"
//! \~russian Возвращает PIByteArray::hash() от "ba"
template<> inline uint piHash(const PIByteArray & ba) {return ba.hash();}
template<>
inline uint piHash(const PIByteArray & ba) {
return ba.hash();
}
//! \relatesalso PIByteArray
//! \~english Swap contents betwee "f" and "s"
//! \~russian Меняет содержимое массивов "f" и "s"
template<> inline void piSwap(PIByteArray & f, PIByteArray & s) {f.swap(s);}
template<>
inline void piSwap(PIByteArray & f, PIByteArray & s) {
f.swap(s);
}
//! \relatesalso PIByteArray
//! \~english Store "value" to bytearray and returns it
//! \~russian Сохраняет "value" в байтовый массив и возвращает его
template <typename T> PIByteArray piSerialize(const T & value) {
template<typename T>
PIByteArray piSerialize(const T & value) {
PIByteArray ret;
ret << value;
return ret;
@@ -1259,7 +1274,8 @@ template <typename T> PIByteArray piSerialize(const T & value) {
//! \relatesalso PIByteArray
//! \~english Restore type "T" from bytearray "data" and returns it
//! \~russian Извлекает тип "T" из байтового массива "data" и возвращает его
template <typename T> T piDeserialize(const PIByteArray & data) {
template<typename T>
T piDeserialize(const PIByteArray & data) {
T ret;
if (!data.isEmpty()) {
PIByteArray ba(data);

View File

@@ -1,33 +1,35 @@
/*
PIP - Platform Independent Primitives
Timer
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Timer
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piincludes_p.h"
#include "pidatetime.h"
#include "piincludes_p.h"
#include <ctime>
#ifdef ARDUINO
# include <Arduino.h>
#endif
#ifdef MAC_OS
//# include <mach/mach_traps.h>
//# include <mach/mach.h>
// # include <mach/mach_traps.h>
// # include <mach/mach.h>
# include <mach/clock.h>
//# include <crt_externs.h>
// # include <crt_externs.h>
#endif
#ifdef MICRO_PIP
# include <sys/time.h>
@@ -51,12 +53,13 @@ PIPair<PIString, PIChar> extractComponent(PIString & str) {
if (str.isEmpty()) return ret;
int ind = str.findAny(valid);
if (ind < 0) return ret;
ret.first = str.takeLeft(ind);
ret.first = str.takeLeft(ind);
ret.second = str.takeLeft(1)[0];
while (str.isNotEmpty()) {
if (str[0] == ret.second)
str.cutLeft(1);
else break;
else
break;
}
return ret;
}
@@ -65,89 +68,108 @@ PIString extractInteger(PIString & str) {
while (str.isNotEmpty()) {
if (str[0].isDigit())
ret += str.takeLeft(1);
else break;
else
break;
}
return ret;
}
bool operator ==(const PITime & t0, const PITime & t1) {
bool operator==(const PITime & t0, const PITime & t1) {
return (t0.hours == t1.hours && t0.minutes == t1.minutes && t0.seconds == t1.seconds);
}
bool operator <(const PITime & t0, const PITime & t1) {
bool operator<(const PITime & t0, const PITime & t1) {
if (t0.hours == t1.hours) {
if (t0.minutes == t1.minutes) {
return t0.seconds < t1.seconds;
} else return t0.minutes < t1.minutes;
} else return t0.hours < t1.hours;
} else
return t0.minutes < t1.minutes;
} else
return t0.hours < t1.hours;
}
bool operator >(const PITime & t0, const PITime & t1) {
bool operator>(const PITime & t0, const PITime & t1) {
if (t0.hours == t1.hours) {
if (t0.minutes == t1.minutes) {
return t0.seconds > t1.seconds;
} else return t0.minutes > t1.minutes;
} else return t0.hours > t1.hours;
} else
return t0.minutes > t1.minutes;
} else
return t0.hours > t1.hours;
}
bool operator ==(const PIDate & t0, const PIDate & t1) {
bool operator==(const PIDate & t0, const PIDate & t1) {
return (t0.year == t1.year && t0.month == t1.month && t0.day == t1.day);
}
bool operator <(const PIDate & t0, const PIDate & t1) {
bool operator<(const PIDate & t0, const PIDate & t1) {
if (t0.year == t1.year) {
if (t0.month == t1.month) {
return t0.day < t1.day;
} else return t0.month < t1.month;
} else return t0.year < t1.year;
} else
return t0.month < t1.month;
} else
return t0.year < t1.year;
}
bool operator >(const PIDate & t0, const PIDate & t1) {
bool operator>(const PIDate & t0, const PIDate & t1) {
if (t0.year == t1.year) {
if (t0.month == t1.month) {
return t0.day > t1.day;
} else return t0.month > t1.month;
} else return t0.year > t1.year;
} else
return t0.month > t1.month;
} else
return t0.year > t1.year;
}
bool operator ==(const PIDateTime & t0, const PIDateTime & t1) {
return (t0.year == t1.year && t0.month == t1.month && t0.day == t1.day &&
t0.hours == t1.hours && t0.minutes == t1.minutes && t0.seconds == t1.seconds);
bool operator==(const PIDateTime & t0, const PIDateTime & t1) {
return (t0.year == t1.year && t0.month == t1.month && t0.day == t1.day && t0.hours == t1.hours && t0.minutes == t1.minutes &&
t0.seconds == t1.seconds);
}
bool operator <(const PIDateTime & t0, const PIDateTime & t1) {
bool operator<(const PIDateTime & t0, const PIDateTime & t1) {
if (t0.year == t1.year) {
if (t0.month == t1.month) {
if (t0.day == t1.day) {
if (t0.hours == t1.hours) {
if (t0.minutes == t1.minutes) {
return t0.seconds < t1.seconds;
} else return t0.minutes < t1.minutes;
} else return t0.hours < t1.hours;
} else return t0.day < t1.day;
} else return t0.month < t1.month;
} else return t0.year < t1.year;
} else
return t0.minutes < t1.minutes;
} else
return t0.hours < t1.hours;
} else
return t0.day < t1.day;
} else
return t0.month < t1.month;
} else
return t0.year < t1.year;
}
bool operator >(const PIDateTime & t0, const PIDateTime & t1) {
bool operator>(const PIDateTime & t0, const PIDateTime & t1) {
if (t0.year == t1.year) {
if (t0.month == t1.month) {
if (t0.day == t1.day) {
if (t0.hours == t1.hours) {
if (t0.minutes == t1.minutes) {
return t0.seconds > t1.seconds;
} else return t0.minutes > t1.minutes;
} else return t0.hours > t1.hours;
} else return t0.day > t1.day;
} else return t0.month > t1.month;
} else return t0.year > t1.year;
} else
return t0.minutes > t1.minutes;
} else
return t0.hours > t1.hours;
} else
return t0.day > t1.day;
} else
return t0.month > t1.month;
} else
return t0.year > t1.year;
}
@@ -180,55 +202,55 @@ PITime PITime::fromString(PIString string, PIString format) {
PITime PITime::current() {
time_t rt = ::time(0);
tm * pt = localtime(&rt);
tm * pt = localtime(&rt);
PITime t;
t.seconds = pt->tm_sec;
t.minutes = pt->tm_min;
t.hours = pt->tm_hour;
t.hours = pt->tm_hour;
return t;
}
PITime PITime::fromSystemTime(const PISystemTime & st) {
double s = st.toSeconds();
int v = s;
int v = s;
PITime ret;
ret.milliseconds = (s - v) * 1000;
ret.seconds = v % 60; v = (v - ret.seconds) / 60;
ret.minutes = v % 60; v = (v - ret.minutes) / 60;
ret.hours = v;
ret.seconds = v % 60;
v = (v - ret.seconds) / 60;
ret.minutes = v % 60;
v = (v - ret.minutes) / 60;
ret.hours = v;
return ret;
}
PIDate PIDate::current() {
time_t rt = ::time(0);
tm * pt = localtime(&rt);
tm * pt = localtime(&rt);
PIDate d;
d.day = pt->tm_mday;
d.day = pt->tm_mday;
d.month = pt->tm_mon + 1;
d.year = pt->tm_year + 1900;
d.year = pt->tm_year + 1900;
return d;
}
PIDateTime PIDateTime::current() {
time_t rt = ::time(0);
tm * pt = localtime(&rt);
tm * pt = localtime(&rt);
PIDateTime dt;
dt.milliseconds = 0;
dt.seconds = pt->tm_sec;
dt.minutes = pt->tm_min;
dt.hours = pt->tm_hour;
dt.day = pt->tm_mday;
dt.month = pt->tm_mon + 1;
dt.year = pt->tm_year + 1900;
dt.seconds = pt->tm_sec;
dt.minutes = pt->tm_min;
dt.hours = pt->tm_hour;
dt.day = pt->tm_mday;
dt.month = pt->tm_mon + 1;
dt.year = pt->tm_year + 1900;
return dt;
}
PIString PITime::toString(const PIString & format) const {
PIString ts = format;
ts.replace("hh", PIString::fromNumber(hours).expandLeftTo(2, '0'));
@@ -303,11 +325,11 @@ PIString PIDateTime::toString(const PIString & format) const {
time_t PIDateTime::toSecondSinceEpoch() const {
tm pt;
memset(&pt, 0, sizeof(pt));
pt.tm_sec = seconds;
pt.tm_min = minutes;
pt.tm_sec = seconds;
pt.tm_min = minutes;
pt.tm_hour = hours;
pt.tm_mday = day;
pt.tm_mon = month - 1;
pt.tm_mon = month - 1;
#ifdef WINDOWS
pt.tm_year = piMaxi(year - 1900, 70);
#else
@@ -347,12 +369,11 @@ PIDateTime PIDateTime::fromSecondSinceEpoch(const time_t sec) {
PIDateTime dt;
dt.seconds = pt->tm_sec;
dt.minutes = pt->tm_min;
dt.hours = pt->tm_hour;
dt.day = pt->tm_mday;
dt.month = pt->tm_mon + 1;
dt.year = pt->tm_year + 1900;
dt.hours = pt->tm_hour;
dt.day = pt->tm_mday;
dt.month = pt->tm_mon + 1;
dt.year = pt->tm_year + 1900;
return dt;
}
@@ -400,9 +421,7 @@ PIString datetime2string(const PIDateTime & date, const PIString & format) {
}
PICout operator <<(PICout s, const PITime & v) {
PICout operator<<(PICout s, const PITime & v) {
s.space();
s.saveAndSetControls(0);
s << "PITime(" << v.hours << ":";
@@ -414,7 +433,7 @@ PICout operator <<(PICout s, const PITime & v) {
}
PICout operator <<(PICout s, const PIDate & v) {
PICout operator<<(PICout s, const PIDate & v) {
s.space();
s.saveAndSetControls(0);
s << "PIDate(" << v.day << "-";
@@ -425,7 +444,7 @@ PICout operator <<(PICout s, const PIDate & v) {
}
PICout operator <<(PICout s, const PIDateTime & v) {
PICout operator<<(PICout s, const PIDateTime & v) {
s.space();
s.saveAndSetControls(0);
s << "PIDateTime(";
@@ -439,4 +458,3 @@ PICout operator <<(PICout s, const PIDateTime & v) {
s.restoreControls();
return s;
}

View File

@@ -3,24 +3,24 @@
* \~\brief
* \~english Time and date structs
* \~russian Типы времени и даты
*/
*/
/*
PIP - Platform Independent Primitives
Time and date structs
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Time and date structs
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIDATETIME_H
@@ -38,7 +38,13 @@ class PIP_EXPORT PITime {
public:
//! \~english Construct %PITime from hours, minutes, seconds and milliseconds
//! \~russian Создает %PITime из часов, минут, секунд и миллисекунд
PITime(int hours_ = 0, int minutes_ = 0, int seconds_ = 0, int milliseconds_ = 0): hours(hours_), minutes(minutes_), seconds(seconds_), milliseconds(milliseconds_) {;}
PITime(int hours_ = 0, int minutes_ = 0, int seconds_ = 0, int milliseconds_ = 0)
: hours(hours_)
, minutes(minutes_)
, seconds(seconds_)
, milliseconds(milliseconds_) {
;
}
//! \~english Returns string representation
//! \~russian Возвращает строковое представление
@@ -80,34 +86,38 @@ public:
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator ==(const PITime & t0, const PITime & t1);
PIP_EXPORT bool operator==(const PITime & t0, const PITime & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator <(const PITime & t0, const PITime & t1);
PIP_EXPORT bool operator<(const PITime & t0, const PITime & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator >(const PITime & t0, const PITime & t1);
PIP_EXPORT bool operator>(const PITime & t0, const PITime & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator !=(const PITime & t0, const PITime & t1) {return !(t0 == t1);}
inline bool operator!=(const PITime & t0, const PITime & t1) {
return !(t0 == t1);
}
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <=(const PITime & t0, const PITime & t1) {return !(t0 > t1);}
inline bool operator<=(const PITime & t0, const PITime & t1) {
return !(t0 > t1);
}
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >=(const PITime & t0, const PITime & t1) {return !(t0 < t1);}
inline bool operator>=(const PITime & t0, const PITime & t1) {
return !(t0 < t1);
}
//! \relatesalso PICout
//! \~english \brief Output operator to PICout
//! \~russian \brief Оператор вывода в PICout
PIP_EXPORT PICout operator <<(PICout s, const PITime & v);
PIP_EXPORT PICout operator<<(PICout s, const PITime & v);
//! \ingroup Types
@@ -118,7 +128,7 @@ class PIP_EXPORT PIDate {
public:
//! \~english Construct %PIDate from year, month and day
//! \~russian Создает %PIDate из года, месяца и дня
PIDate(int year_ = 0, int month_ = 0, int day_ = 0): year(year_), month(month_), day(day_) {;}
PIDate(int year_ = 0, int month_ = 0, int day_ = 0): year(year_), month(month_), day(day_) { ; }
//! \~english Returns string representation
//! \~russian Возвращает строковое представление
@@ -148,34 +158,38 @@ public:
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator ==(const PIDate & t0, const PIDate & t1);
PIP_EXPORT bool operator==(const PIDate & t0, const PIDate & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator <(const PIDate & t0, const PIDate & t1);
PIP_EXPORT bool operator<(const PIDate & t0, const PIDate & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator >(const PIDate & t0, const PIDate & t1);
PIP_EXPORT bool operator>(const PIDate & t0, const PIDate & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator !=(const PIDate & t0, const PIDate & t1) {return !(t0 == t1);}
inline bool operator!=(const PIDate & t0, const PIDate & t1) {
return !(t0 == t1);
}
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <=(const PIDate & t0, const PIDate & t1) {return !(t0 > t1);}
inline bool operator<=(const PIDate & t0, const PIDate & t1) {
return !(t0 > t1);
}
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >=(const PIDate & t0, const PIDate & t1) {return !(t0 < t1);}
inline bool operator>=(const PIDate & t0, const PIDate & t1) {
return !(t0 < t1);
}
//! \relatesalso PICout
//! \~english \brief Output operator to PICout
//! \~russian \brief Оператор вывода в PICout
PIP_EXPORT PICout operator <<(PICout s, const PIDate & v);
PIP_EXPORT PICout operator<<(PICout s, const PIDate & v);
//! \ingroup Types
@@ -186,28 +200,47 @@ class PIP_EXPORT PIDateTime {
public:
//! \~english Construct null %PIDateTime
//! \~russian Создает нулевой %PIDateTime
PIDateTime() {year = month = day = hours = minutes = seconds = milliseconds = 0;}
PIDateTime() { year = month = day = hours = minutes = seconds = milliseconds = 0; }
//! \~english Construct %PIDateTime from %PITime and null %PIDate
//! \~russian Создает %PIDateTime из %PITime и нулевого %PIDate
PIDateTime(const PITime & time) {year = month = day = 0; hours = time.hours; minutes = time.minutes; seconds = time.seconds; milliseconds = time.milliseconds;}
PIDateTime(const PITime & time) {
year = month = day = 0;
hours = time.hours;
minutes = time.minutes;
seconds = time.seconds;
milliseconds = time.milliseconds;
}
//! \~english Construct %PIDateTime from %PIDate and null %PITime
//! \~russian Создает %PIDateTime из %PIDate и нулевого %PITime
PIDateTime(const PIDate & date) {year = date.year; month = date.month; day = date.day; hours = minutes = seconds = milliseconds = 0;}
PIDateTime(const PIDate & date) {
year = date.year;
month = date.month;
day = date.day;
hours = minutes = seconds = milliseconds = 0;
}
//! \~english Construct %PIDateTime from %PIDate and %PITime
//! \~russian Создает %PIDateTime из %PIDate и %PITime
PIDateTime(const PIDate & date, const PITime & time) {year = date.year; month = date.month; day = date.day; hours = time.hours; minutes = time.minutes; seconds = time.seconds; milliseconds = time.milliseconds;}
PIDateTime(const PIDate & date, const PITime & time) {
year = date.year;
month = date.month;
day = date.day;
hours = time.hours;
minutes = time.minutes;
seconds = time.seconds;
milliseconds = time.milliseconds;
}
//! \~english Returns normalized %PIDateTime
//! \~russian Возвращает нормализованный %PIDateTime
PIDateTime normalized() const {return PIDateTime::fromSecondSinceEpoch(toSecondSinceEpoch());}
PIDateTime normalized() const { return PIDateTime::fromSecondSinceEpoch(toSecondSinceEpoch()); }
//! \~english Normalize all fields
//! \~russian Нормализует все поля
void normalize() {*this = normalized();}
void normalize() { *this = normalized(); }
//! \~english Returns string representation
//! \~russian Возвращает строковое представление
@@ -223,31 +256,56 @@ public:
//! \~english Returns time as %PISystemTime
//! \~russian Возвращает время как %PISystemTime
PISystemTime toSystemTime() const {return PISystemTime(int(toSecondSinceEpoch()), milliseconds * 1000000);}
PISystemTime toSystemTime() const { return PISystemTime(int(toSecondSinceEpoch()), milliseconds * 1000000); }
//! \~english Returns date part
//! \~russian Возвращает дату
PIDate date() const {return PIDate(year, month, day);}
PIDate date() const { return PIDate(year, month, day); }
//! \~english Returns time part
//! \~russian Возвращает время
PITime time() const {return PITime(hours, minutes, seconds, milliseconds);}
PITime time() const { return PITime(hours, minutes, seconds, milliseconds); }
//! \~english Set date part
//! \~russian Устанавливает дату
void setDate(const PIDate & d) {year = d.year; month = d.month; day = d.day;}
void setDate(const PIDate & d) {
year = d.year;
month = d.month;
day = d.day;
}
//! \~english Set time part
//! \~russian Устанавливает время
void setTime(const PITime & t) {hours = t.hours; minutes = t.minutes; seconds = t.seconds; milliseconds = t.milliseconds;}
void setTime(const PITime & t) {
hours = t.hours;
minutes = t.minutes;
seconds = t.seconds;
milliseconds = t.milliseconds;
}
//! \~english Sum operator
//! \~russian Оператор сложения
void operator +=(const PIDateTime & d1) {year += d1.year; month += d1.month; day += d1.day; hours += d1.hours; minutes += d1.minutes; seconds += d1.seconds; normalize();}
void operator+=(const PIDateTime & d1) {
year += d1.year;
month += d1.month;
day += d1.day;
hours += d1.hours;
minutes += d1.minutes;
seconds += d1.seconds;
normalize();
}
//! \~english Subtract operator
//! \~russian Оператор вычитания
void operator -=(const PIDateTime & d1) {year -= d1.year; month -= d1.month; day -= d1.day; hours -= d1.hours; minutes -= d1.minutes; seconds -= d1.seconds; normalize();}
void operator-=(const PIDateTime & d1) {
year -= d1.year;
month -= d1.month;
day -= d1.day;
hours -= d1.hours;
minutes -= d1.minutes;
seconds -= d1.seconds;
normalize();
}
//! \~english Construct %PIDateTime from seconds since 1 Jan 1970
//! \~russian Создает %PIDateTime из секунд от 1 Янв 1970
@@ -255,7 +313,11 @@ public:
//! \~english Construct %PIDateTime from %PISystemTime
//! \~russian Создает %PIDateTime из %PISystemTime
static PIDateTime fromSystemTime(const PISystemTime & st) {PIDateTime dt = fromSecondSinceEpoch(st.seconds); dt.milliseconds = piClampi(st.nanoseconds / 1000000, 0, 999); return dt;}
static PIDateTime fromSystemTime(const PISystemTime & st) {
PIDateTime dt = fromSecondSinceEpoch(st.seconds);
dt.milliseconds = piClampi(st.nanoseconds / 1000000, 0, 999);
return dt;
}
//! \~english Returns current date and time
//! \~russian Возвращает текущую дату и время
@@ -293,40 +355,54 @@ public:
//! \~english Sum operator
//! \~russian Оператор сложения
inline PIDateTime operator +(const PIDateTime & d0, const PIDateTime & d1) {PIDateTime td = d0; td += d1; return td.normalized();}
inline PIDateTime operator+(const PIDateTime & d0, const PIDateTime & d1) {
PIDateTime td = d0;
td += d1;
return td.normalized();
}
//! \~english Subtract operator
//! \~russian Оператор вычитания
inline PIDateTime operator -(const PIDateTime & d0, const PIDateTime & d1) {PIDateTime td = d0; td -= d1; return td.normalized();}
inline PIDateTime operator-(const PIDateTime & d0, const PIDateTime & d1) {
PIDateTime td = d0;
td -= d1;
return td.normalized();
}
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator ==(const PIDateTime & t0, const PIDateTime & t1);
PIP_EXPORT bool operator==(const PIDateTime & t0, const PIDateTime & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator <(const PIDateTime & t0, const PIDateTime & t1);
PIP_EXPORT bool operator<(const PIDateTime & t0, const PIDateTime & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
PIP_EXPORT bool operator >(const PIDateTime & t0, const PIDateTime & t1);
PIP_EXPORT bool operator>(const PIDateTime & t0, const PIDateTime & t1);
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator !=(const PIDateTime & t0, const PIDateTime & t1) {return !(t0 == t1);}
inline bool operator!=(const PIDateTime & t0, const PIDateTime & t1) {
return !(t0 == t1);
}
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator <=(const PIDateTime & t0, const PIDateTime & t1) {return !(t0 > t1);}
inline bool operator<=(const PIDateTime & t0, const PIDateTime & t1) {
return !(t0 > t1);
}
//! \~english Compare operator
//! \~russian Оператор сравнения
inline bool operator >=(const PIDateTime & t0, const PIDateTime & t1) {return !(t0 < t1);}
inline bool operator>=(const PIDateTime & t0, const PIDateTime & t1) {
return !(t0 < t1);
}
//! \relatesalso PICout
//! \~english \brief Output operator to PICout
//! \~russian \brief Оператор вывода в PICout
PIP_EXPORT PICout operator <<(PICout s, const PIDateTime & v);
PIP_EXPORT PICout operator<<(PICout s, const PIDateTime & v);
#endif // PIDATETIME_H

View File

@@ -3,24 +3,24 @@
* \~\brief
* \~english General flags class
* \~russian Универсальные флаги
*/
*/
/*
PIP - Platform Independent Primitives
General flags class
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
General flags class
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIFLAGS_H
@@ -54,194 +54,237 @@
template<typename Enum>
class PIFlags {
public:
//! \~english Constructor with flags = 0
//! \~russian Создает нулевые флаги
PIFlags(): flags(0) {;}
PIFlags(): flags(0) { ; }
//! \~english Constructor with flags = Enum "e"
//! \~russian Создает флаги со значением = Enum "e"
PIFlags(Enum e): flags(e) {;}
PIFlags(Enum e): flags(e) { ; }
//! \~english Constructor with flags = int "i"
//! \~russian Создает флаги со значением = int "i"
PIFlags(const int i): flags(i) {;}
PIFlags(const int i): flags(i) { ; }
//! \~english Set flags on positions "f" to value "on"
//! \~russian Устанавливает флаги по позициям "f" в "on"
PIFlags & setFlag(const PIFlags & f, bool on = true) {if (on) flags |= f.flags; else flags &= ~f.flags; return *this;}
PIFlags & setFlag(const PIFlags & f, bool on = true) {
if (on)
flags |= f.flags;
else
flags &= ~f.flags;
return *this;
}
//! \~english Set flag "e" to value "on"
//! \~russian Устанавливает флаг "e" в "on"
PIFlags & setFlag(const Enum & e, bool on = true) {if (on) flags |= e; else flags &= ~e; return *this;}
PIFlags & setFlag(const Enum & e, bool on = true) {
if (on)
flags |= e;
else
flags &= ~e;
return *this;
}
//! \~english Set flag "i" to value "on"
//! \~russian Устанавливает флаг "i" в "on"
PIFlags & setFlag(const int & i, bool on = true) {if (on) flags |= i; else flags &= ~i; return *this;}
PIFlags & setFlag(const int & i, bool on = true) {
if (on)
flags |= i;
else
flags &= ~i;
return *this;
}
//! \~english Assign operator
//! \~russian Оператор присваивания
void operator =(const Enum & e) {flags = e;}
void operator=(const Enum & e) { flags = e; }
//! \~english Assign operator
//! \~russian Оператор присваивания
void operator =(const int & i) {flags = i;}
void operator=(const int & i) { flags = i; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator ==(const PIFlags & f) {return flags == f.flags;}
bool operator==(const PIFlags & f) { return flags == f.flags; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator ==(const Enum & e) {return flags == e;}
bool operator==(const Enum & e) { return flags == e; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator ==(const int i) {return flags == i;}
bool operator==(const int i) { return flags == i; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator !=(const PIFlags & f) {return flags != f.flags;}
bool operator!=(const PIFlags & f) { return flags != f.flags; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator !=(const Enum & e) {return flags != e;}
bool operator!=(const Enum & e) { return flags != e; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator !=(const int i) {return flags != i;}
bool operator!=(const int i) { return flags != i; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >(const PIFlags & f) {return flags > f.flags;}
bool operator>(const PIFlags & f) { return flags > f.flags; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >(const Enum & e) {return flags > e;}
bool operator>(const Enum & e) { return flags > e; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >(const int i) {return flags > i;}
bool operator>(const int i) { return flags > i; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <(const PIFlags & f) {return flags < f.flags;}
bool operator<(const PIFlags & f) { return flags < f.flags; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <(const Enum & e) {return flags < e;}
bool operator<(const Enum & e) { return flags < e; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <(const int i) {return flags < i;}
bool operator<(const int i) { return flags < i; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >=(const PIFlags & f) {return flags >= f.flags;}
bool operator>=(const PIFlags & f) { return flags >= f.flags; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >=(const Enum & e) {return flags >= e;}
bool operator>=(const Enum & e) { return flags >= e; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >=(const int i) {return flags >= i;}
bool operator>=(const int i) { return flags >= i; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <=(const PIFlags & f) {return flags <= f.flags;}
bool operator<=(const PIFlags & f) { return flags <= f.flags; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <=(const Enum & e) {return flags <= e;}
bool operator<=(const Enum & e) { return flags <= e; }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <=(const int i) {return flags <= i;}
bool operator<=(const int i) { return flags <= i; }
//! \~english Bit-wise AND operator
//! \~russian Оператор побитового И
void operator &=(const PIFlags & f) {flags &= f.flags;}
void operator&=(const PIFlags & f) { flags &= f.flags; }
//! \~english Bit-wise AND operator
//! \~russian Оператор побитового И
void operator &=(const Enum & e) {flags &= e;}
void operator&=(const Enum & e) { flags &= e; }
//! \~english Bit-wise AND operator
//! \~russian Оператор побитового И
void operator &=(const int i) {flags &= i;}
void operator&=(const int i) { flags &= i; }
//! \~english Bit-wise OR operator
//! \~russian Оператор побитового ИЛИ
void operator |=(const PIFlags & f) {flags |= f.flags;}
void operator|=(const PIFlags & f) { flags |= f.flags; }
//! \~english Bit-wise OR operator
//! \~russian Оператор побитового ИЛИ
void operator |=(const Enum & e) {flags |= e;}
void operator|=(const Enum & e) { flags |= e; }
//! \~english Bit-wise OR operator
//! \~russian Оператор побитового ИЛИ
void operator |=(const int i) {flags |= i;}
void operator|=(const int i) { flags |= i; }
//! \~english Bit-wise XOR operator
//! \~russian Оператор побитового исключающего ИЛИ
void operator ^=(const PIFlags & f) {flags ^= f.flags;}
void operator^=(const PIFlags & f) { flags ^= f.flags; }
//! \~english Bit-wise XOR operator
//! \~russian Оператор побитового исключающего ИЛИ
void operator ^=(const Enum & e) {flags ^= e;}
void operator^=(const Enum & e) { flags ^= e; }
//! \~english Bit-wise XOR operator
//! \~russian Оператор побитового исключающего ИЛИ
void operator ^=(const int i) {flags ^= i;}
void operator^=(const int i) { flags ^= i; }
//! \~english Bit-wise AND operator
//! \~russian Оператор побитового И
PIFlags operator &(PIFlags f) const {PIFlags tf(flags & f.flags); return tf;}
PIFlags operator&(PIFlags f) const {
PIFlags tf(flags & f.flags);
return tf;
}
//! \~english Bit-wise AND operator
//! \~russian Оператор побитового И
PIFlags operator &(Enum e) const {PIFlags tf(flags & e); return tf;}
PIFlags operator&(Enum e) const {
PIFlags tf(flags & e);
return tf;
}
//! \~english Bit-wise AND operator
//! \~russian Оператор побитового И
PIFlags operator &(int i) const {PIFlags tf(flags & i); return tf;}
PIFlags operator&(int i) const {
PIFlags tf(flags & i);
return tf;
}
//! \~english Bit-wise OR operator
//! \~russian Оператор побитового ИЛИ
PIFlags operator |(PIFlags f) const {PIFlags tf(flags | f.flags); return tf;}
PIFlags operator|(PIFlags f) const {
PIFlags tf(flags | f.flags);
return tf;
}
//! \~english Bit-wise OR operator
//! \~russian Оператор побитового ИЛИ
PIFlags operator |(Enum e) const {PIFlags tf(flags | e); return tf;}
PIFlags operator|(Enum e) const {
PIFlags tf(flags | e);
return tf;
}
//! \~english Bit-wise OR operator
//! \~russian Оператор побитового ИЛИ
PIFlags operator |(int i) const {PIFlags tf(flags | i); return tf;}
PIFlags operator|(int i) const {
PIFlags tf(flags | i);
return tf;
}
//! \~english Bit-wise XOR operator
//! \~russian Оператор побитового исключающего ИЛИ
PIFlags operator ^(PIFlags f) const {PIFlags tf(flags ^ f.flags); return tf;}
PIFlags operator^(PIFlags f) const {
PIFlags tf(flags ^ f.flags);
return tf;
}
//! \~english Bit-wise XOR operator
//! \~russian Оператор побитового исключающего ИЛИ
PIFlags operator ^(Enum e) const {PIFlags tf(flags ^ e); return tf;}
PIFlags operator^(Enum e) const {
PIFlags tf(flags ^ e);
return tf;
}
//! \~english Bit-wise XOR operator
//! \~russian Оператор побитового исключающего ИЛИ
PIFlags operator ^(int i) const {PIFlags tf(flags ^ i); return tf;}
PIFlags operator^(int i) const {
PIFlags tf(flags ^ i);
return tf;
}
//! \~english Test flag operator
//! \~russian Оператор проверки флага
bool operator [](Enum e) const {return (flags & e) == e;}
bool operator[](Enum e) const { return (flags & e) == e; }
//! \~english Implicity conversion to \c int
//! \~russian Оператор неявного преобразования в \c int
operator int() const {return flags;}
operator int() const { return flags; }
private:
int flags;
};
#endif // PIFLAGS_H

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Storage of properties for GUI usage
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Storage of properties for GUI usage
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pipropertystorage.h"
@@ -28,12 +28,14 @@
//! \~english
//! Key-value storage, based on PIVector with PIPropertyStorage::Property elements. Each element in vector
//! contains unique name. You can access property by name with \a propertyValueByName() or \a propertyByName().
//! You can add or replace property by \a addProperty(const Property&) or \a addProperty(const PIString&, const PIVariant&, const PIString&, int).
//! You can add or replace property by \a addProperty(const Property&) or \a addProperty(const PIString&, const PIVariant&, const PIString&,
//! int).
//!
//! \~russian
//! Хранилище свойств ключ-значние, основанный на PIVector с элементами PIPropertyStorage::Property.
//! Каждый элемент имеет уникальное имя. Доступ к свойствам через \a propertyValueByName() или \a propertyByName().
//! Добавление и перезапись свойств через \a addProperty(const Property&) или \a addProperty(const PIString&, const PIVariant&, const PIString&, int).
//! Добавление и перезапись свойств через \a addProperty(const Property&) или \a addProperty(const PIString&, const PIVariant&, const
//! PIString&, int).
//!
//! \~english Example:
//! \~russian Пример:
@@ -49,8 +51,7 @@
bool PIPropertyStorage::isPropertyExists(const PIString & _name) const {
for (uint i = 0; i < props.size(); ++i)
if (props[i].name == _name)
return true;
if (props[i].name == _name) return true;
return false;
}
@@ -121,15 +122,13 @@ int PIPropertyStorage::removePropertiesByFlag(int flag) {
void PIPropertyStorage::updateProperties(const PIVector<PIPropertyStorage::Property> & properties_, int flag_ignore) {
PIMap<PIString, PIVariant> values;
piForeachC(Property & p, props)
if (((p.flags & flag_ignore) != flag_ignore) || (flag_ignore == 0))
values[p.name] = p.value;
if (((p.flags & flag_ignore) != flag_ignore) || (flag_ignore == 0)) values[p.name] = p.value;
props = properties_;
for (uint i = 0; i < props.size(); ++i) {
Property & p(props[i]);
if (values.contains(p.name)) {
PIVariant pv = values[p.name];
if (pv.type() == p.value.type())
p.value = pv;
if (pv.type() == p.value.type()) p.value = pv;
}
}
}
@@ -137,16 +136,14 @@ void PIPropertyStorage::updateProperties(const PIVector<PIPropertyStorage::Prope
PIPropertyStorage::Property PIPropertyStorage::propertyByName(const PIString & name) const {
piForeachC(Property & p, props)
if (p.name == name)
return p;
if (p.name == name) return p;
return Property();
}
PIVariant PIPropertyStorage::propertyValueByName(const PIString & name) const {
piForeachC(Property & p, props)
if (p.name == name)
return p.value;
if (p.name == name) return p.value;
return PIVariant();
}
@@ -185,17 +182,15 @@ bool PIPropertyStorage::setPropertyFlags(const PIString & name, int flags) {
PIPropertyStorage::Property & PIPropertyStorage::operator[](const PIString & name) {
piForeach (Property & p, props)
if (p.name == name)
return p;
piForeach(Property & p, props)
if (p.name == name) return p;
addProperty(name, "");
return props.back();
}
const PIPropertyStorage::Property PIPropertyStorage::operator[](const PIString & name) const {
piForeachC (Property & p, props)
if (p.name == name)
return p;
piForeachC(Property & p, props)
if (p.name == name) return p;
return Property();
}

View File

@@ -5,22 +5,22 @@
* \~russian Массив свойств
*/
/*
PIP - Platform Independent Primitives
Storage of properties for GUI usage
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Storage of properties for GUI usage
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIPROPERTYSTORAGE_H
@@ -35,7 +35,6 @@
//! \~russian Этот класс предоставляет ключ-значение хранение свойств.
class PIP_EXPORT PIPropertyStorage {
public:
//! \~english Contructs an empty %PIPropertyStorage
//! \~russian Создает пустой %PIPropertyStorage
PIPropertyStorage() {}
@@ -45,48 +44,54 @@ public:
//! \~english PIPropertyStorage element.
//! \~russian Элемент PIPropertyStorage.
struct PIP_EXPORT Property {
//! \~english Contructs %PIPropertyStorage::Property with name "n", comment "c", value "v" and flags "f"
//! \~russian Создает %PIPropertyStorage::Property с именем "n", комментарием "c", значением "v" и флагами "f"
Property(const PIString & n = PIString(), const PIString & c = PIString(), const PIVariant & v = PIVariant(), int f = 0): name(n), comment(c), value(v), flags(f) {}
Property(const PIString & n = PIString(), const PIString & c = PIString(), const PIVariant & v = PIVariant(), int f = 0)
: name(n)
, comment(c)
, value(v)
, flags(f) {}
//! \~english Contructs copy of another %PIPropertyStorage::Property "o"
//! \~russian Создает копию %PIPropertyStorage::Property "o"
Property(const Property & o): name(o.name), comment(o.comment), value(o.value), flags(o.flags) {}
Property(Property && o) {swap(o);}
Property(Property && o) { swap(o); }
//! \~english Assign operator
//! \~russian Оператор присваивания
Property & operator =(const Property & v) {
name = v.name;
Property & operator=(const Property & v) {
name = v.name;
comment = v.comment;
value = v.value;
flags = v.flags;
value = v.value;
flags = v.flags;
return *this;
}
Property & operator=(Property && v) {
swap(v);
return *this;
}
Property & operator =(Property && v) {swap(v); return *this;}
//! \~english Returns value as boolean
//! \~russian Возвращает значение как логическое
bool toBool() const {return value.toBool();}
bool toBool() const { return value.toBool(); }
//! \~english Returns value as integer
//! \~russian Возвращает значение как целое
int toInt() const {return value.toInt();}
int toInt() const { return value.toInt(); }
//! \~english Returns value as float
//! \~russian Возвращает значение как float
float toFloat() const {return value.toFloat();}
float toFloat() const { return value.toFloat(); }
//! \~english Returns value as double
//! \~russian Возвращает значение как double
double toDouble() const {return value.toDouble();}
double toDouble() const { return value.toDouble(); }
//! \~english Returns value as string
//! \~russian Возвращает значение как строку
PIString toString() const {return value.toString();}
PIString toString() const { return value.toString(); }
void swap(Property & o) {
name.swap(o.name);
@@ -114,7 +119,7 @@ public:
//! \~english Contructs %PIPropertyStorage with "pl" properties
//! \~russian Создает %PIPropertyStorage со свойствами "pl"
PIPropertyStorage(const PIVector<Property> & pl) {props = pl;}
PIPropertyStorage(const PIVector<Property> & pl) { props = pl; }
//! \~english Contructs %PIPropertyStorage from another "o"
//! \~russian Создает %PIPropertyStorage из другого "o"
@@ -124,69 +129,69 @@ public:
typedef PIVector<Property>::iterator iterator;
typedef Property value_type;
iterator begin() {return props.begin();}
const_iterator begin() const {return props.begin();}
iterator end() {return props.end();}
const_iterator end() const {return props.end();}
iterator begin() { return props.begin(); }
const_iterator begin() const { return props.begin(); }
iterator end() { return props.end(); }
const_iterator end() const { return props.end(); }
//! \~english Returns properties count
//! \~russian Возвращает количество свойств
int length() const {return props.length();}
int length() const { return props.length(); }
//! \~english Returns properties count
//! \~russian Возвращает количество свойств
int size() const {return props.size();}
int size() const { return props.size(); }
//! \~english Returns if no properties
//! \~russian Возвращает нет ли свойств
bool isEmpty() const {return props.isEmpty();}
bool isEmpty() const { return props.isEmpty(); }
//! \~english Returns if properties
//! \~russian Возвращает есть ли свойства
bool isNotEmpty() const {return props.isNotEmpty();}
bool isNotEmpty() const { return props.isNotEmpty(); }
//! \~english Returns first property
//! \~russian Возвращает первое свойство
Property & front() {return props.front();}
Property & front() { return props.front(); }
//! \~english Returns first property as const
//! \~russian Возвращает первое свойство как константу
const Property & front() const {return props.front();}
const Property & front() const { return props.front(); }
//! \~english Returns last property
//! \~russian Возвращает последнее свойство
Property & back() {return props.back();}
Property & back() { return props.back(); }
//! \~english Returns last property as const
//! \~russian Возвращает последнее свойство как константу
const Property & back() const {return props.back();}
const Property & back() const { return props.back(); }
//! \~english Remove property at index "i"
//! \~russian Удаляет свойство по индексу "i"
void removeAt(int i) {props.remove(i);}
void removeAt(int i) { props.remove(i); }
//! \~english Remove all properties
//! \~russian Удаляет все свойства
void clear() {props.clear();}
void clear() { props.clear(); }
//! \~english Returns copy of this %PIPropertyStorage
//! \~russian Возвращает копию этого %PIPropertyStorage
PIPropertyStorage copy() const {return PIPropertyStorage(*this);}
PIPropertyStorage copy() const { return PIPropertyStorage(*this); }
//! \~english Returns properties count
//! \~russian Возвращает количество свойств
int propertiesCount() const {return props.size();}
int propertiesCount() const { return props.size(); }
//! \~english Returns properties as PIVector
//! \~russian Возвращает свойства как PIVector
PIVector<Property> & properties() {return props;}
PIVector<Property> & properties() { return props; }
//! \~english Returns properties as const PIVector
//! \~russian Возвращает свойства как константный PIVector
const PIVector<Property> & properties() const {return props;}
const PIVector<Property> & properties() const { return props; }
const PIPropertyStorage & propertyStorage() const {return *this;}
const PIPropertyStorage & propertyStorage() const { return *this; }
//! \~english Returns if properties with name "name" exists
//! \~russian Возвращает присутствует ли свойство с именем "name"
@@ -194,7 +199,7 @@ public:
//! \~english Remove all properties
//! \~russian Удаляет все свойства
void clearProperties() {props.clear();}
void clearProperties() { props.clear(); }
//! \~english Add property if name isn't present in storage, otherwrise update existing property with same name
//! \~russian Добавляет новое свойство, если его имени не было в контейнере, иначе обновляет существующее свойство с этим именем
@@ -239,23 +244,32 @@ public:
//! \~english Add property "p"
//! \~russian Добавляет свойство "p"
PIPropertyStorage & operator <<(const PIPropertyStorage::Property & p) {props << p; return *this;}
PIPropertyStorage & operator<<(const PIPropertyStorage::Property & p) {
props << p;
return *this;
}
//! \~english Add properties "p"
//! \~russian Добавляет свойства "p"
PIPropertyStorage & operator <<(const PIVector<Property> & p) {props << p; return *this;}
PIPropertyStorage & operator<<(const PIVector<Property> & p) {
props << p;
return *this;
}
//! \~english Add properties "p"
//! \~russian Добавляет свойства "p"
PIPropertyStorage & operator <<(const PIPropertyStorage & p) {props << p.props; return *this;}
PIPropertyStorage & operator<<(const PIPropertyStorage & p) {
props << p.props;
return *this;
}
//! \~english Returns property with index "i"
//! \~russian Возвращает свойство по индексу "i"
Property & operator[](int i) {return props[i];}
Property & operator[](int i) { return props[i]; }
//! \~english Returns property with index "i" as const
//! \~russian Возвращает свойство по индексу "i" как константу
const Property & operator[](int i) const {return props[i];}
const Property & operator[](int i) const { return props[i]; }
//! \~english Returns property with name "name"
//! \~russian Возвращает свойство с именем "name"
@@ -267,30 +281,41 @@ public:
protected:
PIVector<Property> props;
};
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIPropertyStorage::Property) {s << v.name << v.value << v.comment << v.flags; return s;}
BINARY_STREAM_WRITE(PIPropertyStorage::Property) {
s << v.name << v.value << v.comment << v.flags;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIPropertyStorage::Property) {s >> v.name >> v.value >> v.comment >> v.flags; return s;}
BINARY_STREAM_READ(PIPropertyStorage::Property) {
s >> v.name >> v.value >> v.comment >> v.flags;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIPropertyStorage) {s << v.properties(); return s;}
BINARY_STREAM_WRITE(PIPropertyStorage) {
s << v.properties();
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIPropertyStorage) {s >> v.properties(); return s;}
BINARY_STREAM_READ(PIPropertyStorage) {
s >> v.properties();
return s;
}
#endif // PIPROPERTYSTORAGE_H

View File

@@ -1,25 +1,27 @@
/*
PIP - Platform Independent Primitives
Unix time
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Unix time
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piincludes_p.h"
#include "pisystemtime.h"
#include "piincludes_p.h"
#include "pitime.h"
#include <ctime>
#ifdef QNX
# include <time.h>
@@ -30,15 +32,19 @@
# include <Arduino.h>
#endif
#ifdef WINDOWS
extern FILETIME __pi_ftjan1970;
long long __PIQueryPerformanceCounter() {LARGE_INTEGER li; QueryPerformanceCounter(&li); return li.QuadPart;}
extern FILETIME __pi_ftjan1970;
long long __PIQueryPerformanceCounter() {
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return li.QuadPart;
}
#endif
#ifdef MAC_OS
//# include <mach/mach_traps.h>
//# include <mach/mach.h>
// # include <mach/mach_traps.h>
// # include <mach/mach.h>
# include <mach/clock.h>
//# include <crt_externs.h>
extern clock_serv_t __pi_mac_clock;
// # include <crt_externs.h>
extern clock_serv_t __pi_mac_clock;
#endif
#ifdef MICRO_PIP
# include <sys/time.h>
@@ -87,8 +93,6 @@
//!
//! \details
//! \warning
//! \~english
@@ -105,8 +109,8 @@ void PISystemTime::sleep() {
void PISystemTime::toTimespec(void * ts) {
#ifndef WINDOWS
((timespec*)ts)->tv_sec = seconds;
((timespec*)ts)->tv_nsec = nanoseconds;
((timespec *)ts)->tv_sec = seconds;
((timespec *)ts)->tv_nsec = nanoseconds;
#endif
}
@@ -150,16 +154,16 @@ PISystemTime PISystemTime::current(bool precise_but_not_system) {
#elif defined(MICRO_PIP)
timespec t_cur;
# ifdef ARDUINO
static const uint32_t offSetSinceEpoch_s = 1581897605UL;
uint32_t mt = millis();
t_cur.tv_sec = offSetSinceEpoch_s + (mt / 1000);
t_cur.tv_nsec = (mt - (mt / 1000)) * 1000000UL;
static const uint32_t offSetSinceEpoch_s = 1581897605UL;
uint32_t mt = millis();
t_cur.tv_sec = offSetSinceEpoch_s + (mt / 1000);
t_cur.tv_nsec = (mt - (mt / 1000)) * 1000000UL;
# else
timeval tv;
tv.tv_sec = 0;
tv.tv_sec = 0;
tv.tv_usec = 0;
gettimeofday(&tv, NULL);
t_cur.tv_sec = tv.tv_sec;
t_cur.tv_sec = tv.tv_sec;
t_cur.tv_nsec = tv.tv_usec * 1000;
# endif
#else
@@ -172,7 +176,6 @@ PISystemTime PISystemTime::current(bool precise_but_not_system) {
}
PITimeMeasurer::PITimeMeasurer() {
reset();
}
@@ -181,36 +184,36 @@ PITimeMeasurer::PITimeMeasurer() {
double PITimeMeasurer::elapsed_n() const {
return (PISystemTime::current(true) - t_st).toNanoseconds()
#ifndef MICRO_PIP
- PISystemTests::time_elapsed_ns
- PISystemTests::time_elapsed_ns
#endif
;
;
}
double PITimeMeasurer::elapsed_u() const {
return (PISystemTime::current(true) - t_st).toMicroseconds()
#ifndef MICRO_PIP
- PISystemTests::time_elapsed_ns / 1.E+3
- PISystemTests::time_elapsed_ns / 1.E+3
#endif
;
;
}
double PITimeMeasurer::elapsed_m() const {
return (PISystemTime::current(true) - t_st).toMilliseconds()
#ifndef MICRO_PIP
- PISystemTests::time_elapsed_ns / 1.E+6
- PISystemTests::time_elapsed_ns / 1.E+6
#endif
;
;
}
double PITimeMeasurer::elapsed_s() const {
return (PISystemTime::current(true) - t_st).toSeconds()
#ifndef MICRO_PIP
- PISystemTests::time_elapsed_ns / 1.E+9
- PISystemTests::time_elapsed_ns / 1.E+9
#endif
;
;
}

View File

@@ -3,24 +3,24 @@
* \~\brief
* \~english System time structs and methods
* \~russian Типы и методы системного времени
*/
*/
/*
PIP - Platform Independent Primitives
Time structs
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Time structs
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PISYSTEMTIME_H
@@ -36,159 +36,238 @@
//! \~russian Системное время с точностью до наносекунд.
class PIP_EXPORT PISystemTime {
public:
//! \~english Contructs time with seconds and nanoseconds = 0
//! \~russian Создает время с секундами и наносекундами = 0
PISystemTime() {seconds = nanoseconds = 0;}
PISystemTime() { seconds = nanoseconds = 0; }
//! \~english Contructs time with "s" seconds and "ns" nanoseconds
//! \~russian Создает время с секундами "s" и наносекундами "ns"
PISystemTime(int s, int ns) {seconds = s; nanoseconds = ns; checkOverflows();}
PISystemTime(int s, int ns) {
seconds = s;
nanoseconds = ns;
checkOverflows();
}
//! \~english Returns time value in seconds
//! \~russian Возвращает значение времени в секундах
double toSeconds() const {return double(seconds) + nanoseconds / 1.e+9;}
double toSeconds() const { return double(seconds) + nanoseconds / 1.e+9; }
//! \~english Returns time value in milliseconds
//! \~russian Возвращает значение времени в миллисекундах
double toMilliseconds() const {return seconds * 1.e+3 + nanoseconds / 1.e+6;}
double toMilliseconds() const { return seconds * 1.e+3 + nanoseconds / 1.e+6; }
//! \~english Returns time value in microseconds
//! \~russian Возвращает значение времени в микросекундах
double toMicroseconds() const {return seconds * 1.e+6 + nanoseconds / 1.e+3;}
double toMicroseconds() const { return seconds * 1.e+6 + nanoseconds / 1.e+3; }
//! \~english Returns time value in nanoseconds
//! \~russian Возвращает значение времени в наносекундах
double toNanoseconds() const {return seconds * 1.e+9 + double(nanoseconds);}
double toNanoseconds() const { return seconds * 1.e+9 + double(nanoseconds); }
//! \~english Add to time "v" seconds
//! \~russian Добавляет ко времени "v" секунд
PISystemTime & addSeconds(double v) {*this += fromSeconds(v); return *this;}
PISystemTime & addSeconds(double v) {
*this += fromSeconds(v);
return *this;
}
//! \~english Add to time "v" milliseconds
//! \~russian Добавляет ко времени "v" миллисекунд
PISystemTime & addMilliseconds(double v) {*this += fromMilliseconds(v); return *this;}
PISystemTime & addMilliseconds(double v) {
*this += fromMilliseconds(v);
return *this;
}
//! \~english Add to time "v" microseconds
//! \~russian Добавляет ко времени "v" микросекунд
PISystemTime & addMicroseconds(double v) {*this += fromMicroseconds(v); return *this;}
PISystemTime & addMicroseconds(double v) {
*this += fromMicroseconds(v);
return *this;
}
//! \~english Add to time "v" nanoseconds
//! \~russian Добавляет ко времени "v" наносекунд
PISystemTime & addNanoseconds(double v) {*this += fromNanoseconds(v); return *this;}
PISystemTime & addNanoseconds(double v) {
*this += fromNanoseconds(v);
return *this;
}
//! \~english Sleep for this time
//! \~russian Ожидать это время
void sleep();
//! \~english On *nix system assign current value to timespec struct
//! \~russian На *nix системах присваивает время к timespec структуре
void toTimespec(void * ts);
//! \~english Returns copy of this time with absolutely values of s and ns
//! \~russian Возвращает копию времени с модулем значения
PISystemTime abs() const;
//! \~english Returns sum of this time with "t"
//! \~russian Возвращает сумму этого времени с "t"
PISystemTime operator +(const PISystemTime & t) const {PISystemTime tt(*this); tt.seconds += t.seconds; tt.nanoseconds += t.nanoseconds; tt.checkOverflows(); return tt;}
PISystemTime operator+(const PISystemTime & t) const {
PISystemTime tt(*this);
tt.seconds += t.seconds;
tt.nanoseconds += t.nanoseconds;
tt.checkOverflows();
return tt;
}
//! \~english Returns difference between this time and "t"
//! \~russian Возвращает разницу между этим временем и "t"
PISystemTime operator -(const PISystemTime & t) const {PISystemTime tt(*this); tt.seconds -= t.seconds; tt.nanoseconds -= t.nanoseconds; tt.checkOverflows(); return tt;}
PISystemTime operator-(const PISystemTime & t) const {
PISystemTime tt(*this);
tt.seconds -= t.seconds;
tt.nanoseconds -= t.nanoseconds;
tt.checkOverflows();
return tt;
}
//! \~english Returns multiplication between this time and "t"
//! \~russian Возвращает это временя умноженное на "t"
PISystemTime operator *(const double & v) const {return fromMilliseconds(toMilliseconds() * v);}
PISystemTime operator*(const double & v) const { return fromMilliseconds(toMilliseconds() * v); }
//! \~english Returns division between this time and "t"
//! \~russian Возвращает это временя поделённое на "t"
PISystemTime operator /(const double & v) const {return fromMilliseconds(toMilliseconds() / v);}
PISystemTime operator/(const double & v) const { return fromMilliseconds(toMilliseconds() / v); }
//! \~english Add to time "t"
//! \~russian Добавляет ко времени "t"
PISystemTime & operator +=(const PISystemTime & t) {seconds += t.seconds; nanoseconds += t.nanoseconds; checkOverflows(); return *this;}
PISystemTime & operator+=(const PISystemTime & t) {
seconds += t.seconds;
nanoseconds += t.nanoseconds;
checkOverflows();
return *this;
}
//! \~english Subtract from time "t"
//! \~russian Вычитает из времени "t"
PISystemTime & operator -=(const PISystemTime & t) {seconds -= t.seconds; nanoseconds -= t.nanoseconds; checkOverflows(); return *this;}
PISystemTime & operator-=(const PISystemTime & t) {
seconds -= t.seconds;
nanoseconds -= t.nanoseconds;
checkOverflows();
return *this;
}
//! \~english Multiply time by "v"
//! \~russian Умножает время на "v"
PISystemTime & operator *=(const double & v) {*this = fromMilliseconds(toMilliseconds() * v); return *this;}
PISystemTime & operator*=(const double & v) {
*this = fromMilliseconds(toMilliseconds() * v);
return *this;
}
//! \~english Divide time by "v"
//! \~russian Делит время на "v"
PISystemTime & operator /=(const double & v) {*this = fromMilliseconds(toMilliseconds() / v); return *this;}
PISystemTime & operator/=(const double & v) {
*this = fromMilliseconds(toMilliseconds() / v);
return *this;
}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator ==(const PISystemTime & t) const {return ((seconds == t.seconds) && (nanoseconds == t.nanoseconds));}
bool operator==(const PISystemTime & t) const { return ((seconds == t.seconds) && (nanoseconds == t.nanoseconds)); }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator !=(const PISystemTime & t) const {return ((seconds != t.seconds) || (nanoseconds != t.nanoseconds));}
bool operator!=(const PISystemTime & t) const { return ((seconds != t.seconds) || (nanoseconds != t.nanoseconds)); }
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >(const PISystemTime & t) const {if (seconds == t.seconds) return nanoseconds > t.nanoseconds; return seconds > t.seconds;}
bool operator>(const PISystemTime & t) const {
if (seconds == t.seconds) return nanoseconds > t.nanoseconds;
return seconds > t.seconds;
}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <(const PISystemTime & t) const {if (seconds == t.seconds) return nanoseconds < t.nanoseconds; return seconds < t.seconds;}
bool operator<(const PISystemTime & t) const {
if (seconds == t.seconds) return nanoseconds < t.nanoseconds;
return seconds < t.seconds;
}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator >=(const PISystemTime & t) const {if (seconds == t.seconds) return nanoseconds >= t.nanoseconds; return seconds >= t.seconds;}
bool operator>=(const PISystemTime & t) const {
if (seconds == t.seconds) return nanoseconds >= t.nanoseconds;
return seconds >= t.seconds;
}
//! \~english Compare operator
//! \~russian Оператор сравнения
bool operator <=(const PISystemTime & t) const {if (seconds == t.seconds) return nanoseconds <= t.nanoseconds; return seconds <= t.seconds;}
bool operator<=(const PISystemTime & t) const {
if (seconds == t.seconds) return nanoseconds <= t.nanoseconds;
return seconds <= t.seconds;
}
//! \~english Contructs time from seconds "v"
//! \~russian Создает время из "v" секунд
static PISystemTime fromSeconds(double v) {int s = piFloord(v); return PISystemTime(s, int((v - s) * 1000000000.));}
static PISystemTime fromSeconds(double v) {
int s = piFloord(v);
return PISystemTime(s, int((v - s) * 1000000000.));
}
//! \~english Contructs time from milliseconds "v"
//! \~russian Создает время из "v" миллисекунд
static PISystemTime fromMilliseconds(double v) {int s = piFloord(v / 1000.); return PISystemTime(s, int((v / 1000. - s) * 1000000000.));}
static PISystemTime fromMilliseconds(double v) {
int s = piFloord(v / 1000.);
return PISystemTime(s, int((v / 1000. - s) * 1000000000.));
}
//! \~english Contructs time from microseconds "v"
//! \~russian Создает время из "v" микросекунд
static PISystemTime fromMicroseconds(double v) {int s = piFloord(v / 1000000.); return PISystemTime(s, int((v / 1000000. - s) * 1000000000.));}
static PISystemTime fromMicroseconds(double v) {
int s = piFloord(v / 1000000.);
return PISystemTime(s, int((v / 1000000. - s) * 1000000000.));
}
//! \~english Contructs time from nanoseconds "v"
//! \~russian Создает время из "v" наносекунд
static PISystemTime fromNanoseconds(double v) {int s = piFloord(v / 1000000000.); return PISystemTime(s, int((v / 1000000000. - s) * 1000000000.));}
static PISystemTime fromNanoseconds(double v) {
int s = piFloord(v / 1000000000.);
return PISystemTime(s, int((v / 1000000000. - s) * 1000000000.));
}
//! \~english Returns current system time
//! \~russian Возвращает текущее системное время
static PISystemTime current(bool precise_but_not_system = false);
//! \~english Seconds time part
//! \~russian Секунды времени
int seconds;
//! \~english Nanoseconds time part
//! \~russian Наносекунды времени
int nanoseconds;
private:
void checkOverflows() {while (nanoseconds >= 1000000000) {nanoseconds -= 1000000000; seconds++;} while (nanoseconds < 0) {nanoseconds += 1000000000; seconds--;}}
void checkOverflows() {
while (nanoseconds >= 1000000000) {
nanoseconds -= 1000000000;
seconds++;
}
while (nanoseconds < 0) {
nanoseconds += 1000000000;
seconds--;
}
}
};
//! \relatesalso PICout
//! \~english \brief Output operator to PICout
//! \~russian \brief Оператор вывода в PICout
inline PICout operator <<(PICout s, const PISystemTime & v) {s.space(); s.saveAndSetControls(0); s << "(" << v.seconds << " s, " << v.nanoseconds << " ns)"; s.restoreControls(); return s;}
inline PICout operator<<(PICout s, const PISystemTime & v) {
s.space();
s.saveAndSetControls(0);
s << "(" << v.seconds << " s, " << v.nanoseconds << " ns)";
s.restoreControls();
return s;
}
//! \ingroup Types
@@ -198,15 +277,15 @@ inline PICout operator <<(PICout s, const PISystemTime & v) {s.space(); s.saveAn
class PIP_EXPORT PITimeMeasurer {
public:
PITimeMeasurer();
/** \brief Set internal time mark to current system time
* \details This function used for set start time mark. Later
* you can find out elapsed time from this time mark to any
* moment of time with \a elapsed_s(), \a elapsed_m(),
* \a elapsed_u() or \a elapsed_n() functions.
* \sa \a elapsed_s(), \a elapsed_m(), \a elapsed_u(), \a elapsed_n() */
void reset() {t_st = PISystemTime::current(true);}
void reset() { t_st = PISystemTime::current(true); }
//! \brief Returns nanoseconds elapsed from last \a reset() execution or from timer measurer creation.
double elapsed_n() const;
@@ -221,33 +300,32 @@ public:
//! \brief Returns PISystemTime elapsed from last \a reset() execution or from timer measurer creation.
PISystemTime elapsed() const;
double reset_time_n() const {return t_st.toNanoseconds();}
double reset_time_u() const {return t_st.toMicroseconds();}
double reset_time_m() const {return t_st.toMilliseconds();}
double reset_time_s() const {return t_st.toSeconds();}
double reset_time_n() const { return t_st.toNanoseconds(); }
double reset_time_u() const { return t_st.toMicroseconds(); }
double reset_time_m() const { return t_st.toMilliseconds(); }
double reset_time_s() const { return t_st.toSeconds(); }
//! \brief Returns time mark of last \a reset() execution or timer measurer creation.
PISystemTime reset_time() {return t_st;}
PISystemTime reset_time() { return t_st; }
//! \brief Returns nanoseconds representation of current system time.
static double elapsed_system_n() {return PISystemTime::current(true).toNanoseconds();}
static double elapsed_system_n() { return PISystemTime::current(true).toNanoseconds(); }
//! \brief Returns microseconds representation of current system time.
static double elapsed_system_u() {return PISystemTime::current(true).toMicroseconds();}
static double elapsed_system_u() { return PISystemTime::current(true).toMicroseconds(); }
//! \brief Returns milliseconds representation of current system time.
static double elapsed_system_m() {return PISystemTime::current(true).toMilliseconds();}
static double elapsed_system_m() { return PISystemTime::current(true).toMilliseconds(); }
//! \brief Returns seconds representation of current system time.
static double elapsed_system_s() {return PISystemTime::current(true).toSeconds();}
static double elapsed_system_s() { return PISystemTime::current(true).toSeconds(); }
//! \brief Returns time mark of current system time.
static PISystemTime elapsed_system() {return PISystemTime::current(true);}
static PISystemTime elapsed_system() { return PISystemTime::current(true); }
private:
PISystemTime t_st, t_cur;
};
#endif // PITIME_H

View File

@@ -1,23 +1,24 @@
/*
PIP - Platform Independent Primitives
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "piincludes_p.h"
#include "pitime.h"
#include "piincludes_p.h"
#ifdef QNX
# include <time.h>
#endif
@@ -47,9 +48,9 @@
void piUSleep(int usecs) {
if (usecs <= 0) return;
#ifdef WINDOWS
//printf("Sleep %d\n", usecs / 1000);
// printf("Sleep %d\n", usecs / 1000);
if (usecs > 0) Sleep(usecs / 1000);
//printf("Sleep end");
// printf("Sleep end");
#else
# ifdef FREERTOS
vTaskDelay(usecs / 1000 / portTICK_PERIOD_MS);

View File

@@ -3,23 +3,23 @@
* \~\brief
* \~english System time, time and date
* \~russian Системное время, время и дата
*/
*/
/*
PIP - Platform Independent Primitives
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PITIME_H
@@ -39,7 +39,9 @@ PIP_EXPORT void piUSleep(int usecs); // on !Windows consider constant "usleep" o
//! \~\details
//! \~english This function exec \a piUSleep (msecs * 1000)
//! \~russian Этот метод вызывает \a piUSleep (msecs * 1000)
inline void piMSleep(double msecs) {piUSleep(int(msecs * 1000.));} // on !Windows consider constant "usleep" offset
inline void piMSleep(double msecs) {
piUSleep(int(msecs * 1000.));
} // on !Windows consider constant "usleep" offset
//! \ingroup Types
//! \brief
@@ -48,11 +50,15 @@ inline void piMSleep(double msecs) {piUSleep(int(msecs * 1000.));} // on !Window
//! \~\details
//! \~english This function exec \a piUSleep (msecs * 1000000)
//! \~russian Этот метод вызывает \a piUSleep (msecs * 1000000)
inline void piSleep(double secs) {piUSleep(int(secs * 1000000.));} // on !Windows consider constant "usleep" offset
inline void piSleep(double secs) {
piUSleep(int(secs * 1000000.));
} // on !Windows consider constant "usleep" offset
//! \ingroup Types
//! \~english Shortest available on current system sleep
//! \~russian Наименее возможное для данной системы по длительности ожидание
inline void piMinSleep() {piMSleep(PIP_MIN_MSLEEP);}
inline void piMinSleep() {
piMSleep(PIP_MIN_MSLEEP);
}
#endif // PITIME_H

View File

@@ -3,24 +3,24 @@
* \brief
* \~english PITime conversions for Windows
* \~russian Преобразования PITime для Windows
*/
*/
/*
PIP - Platform Independent Primitives
PITime conversions for Windows
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
PITime conversions for Windows
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PITIME_WIN_H
#define PITIME_WIN_H
@@ -28,21 +28,21 @@
#include "pibase.h"
#ifdef WINDOWS
#include "pitime.h"
#include <windows.h>
# include "pitime.h"
# include <windows.h>
inline PISystemTime FILETIME2PISystemTime(const FILETIME &t) {
inline PISystemTime FILETIME2PISystemTime(const FILETIME & t) {
PISystemTime st;
ullong lt = ullong(t.dwHighDateTime) * 0x100000000U + ullong(t.dwLowDateTime);
st.seconds = lt / 10000000U;
ullong lt = ullong(t.dwHighDateTime) * 0x100000000U + ullong(t.dwLowDateTime);
st.seconds = lt / 10000000U;
st.nanoseconds = (lt % 10000000U) * 100U;
return st;
}
inline PIDateTime SYSTEMTIME2PIDateTime(const SYSTEMTIME &t) {
inline PIDateTime SYSTEMTIME2PIDateTime(const SYSTEMTIME & t) {
PIDateTime dt;
dt.year = t.wYear;
dt.month = t.wMonth;
@@ -54,7 +54,7 @@ inline PIDateTime SYSTEMTIME2PIDateTime(const SYSTEMTIME &t) {
return dt;
}
inline PIDateTime FILETIME2PIDateTime(const FILETIME &t) {
inline PIDateTime FILETIME2PIDateTime(const FILETIME & t) {
FILETIME lt;
SYSTEMTIME st;
FileTimeToLocalFileTime(&t, &lt);
@@ -62,7 +62,7 @@ inline PIDateTime FILETIME2PIDateTime(const FILETIME &t) {
return SYSTEMTIME2PIDateTime(st);
}
inline SYSTEMTIME PIDateTime2SYSTEMTIME(const PIDateTime &dt) {
inline SYSTEMTIME PIDateTime2SYSTEMTIME(const PIDateTime & dt) {
SYSTEMTIME st;
st.wYear = dt.year;
st.wMonth = dt.month;
@@ -74,7 +74,7 @@ inline SYSTEMTIME PIDateTime2SYSTEMTIME(const PIDateTime &dt) {
return st;
}
inline FILETIME PIDateTime2FILETIME(const PIDateTime &dt) {
inline FILETIME PIDateTime2FILETIME(const PIDateTime & dt) {
FILETIME lt, ret;
SYSTEMTIME st = PIDateTime2SYSTEMTIME(dt);
SystemTimeToFileTime(&st, &lt);
@@ -83,6 +83,5 @@ inline FILETIME PIDateTime2FILETIME(const PIDateTime &dt) {
}
#endif // WINDOWS
#endif // PITIME_WIN_H

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Module includes
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Module includes
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! \defgroup Types Types
//! \~\brief
@@ -54,9 +54,9 @@
#include "pibitarray.h"
#include "pibytearray.h"
#include "piflags.h"
#include "pitime.h"
#include "pipropertystorage.h"
#include "pivariantsimple.h"
#include "pitime.h"
#include "pivaluetree.h"
#include "pivariantsimple.h"
#endif // PITYPESMODULE_H

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Attributed values tree
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Attributed values tree
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pivaluetree.h"

View File

@@ -5,22 +5,22 @@
* \~russian Дерево атрибутированных значений
*/
/*
PIP - Platform Independent Primitives
Attributed values tree
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Attributed values tree
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIVALUETREE_H

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Variant type
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Variant type
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pivariant.h"
@@ -232,11 +232,11 @@ PIVariant::Type PIVariant::typeFromName(const PIString & tname) {
if (s == "complexld" || s == "complex<ldouble>" || s == "complex<longdouble>") return PIVariant::pivComplexld;
if (s == "pibitarray" || s == "bitarray") return PIVariant::pivBitArray;
if (s == "pibytearray" || s == "bytearray" || s == "vector<uchar>" || s == "pivector<uchar>" || s == "vector<unsignedchar>" ||
s == "pivector<unsignedchar>" || s == "vector<char>" || s == "pivector<char>")
s == "pivector<unsignedchar>" || s == "vector<char>" || s == "pivector<char>")
return PIVariant::pivByteArray;
if (s == "pistring" || s == "string" || s == "text") return PIVariant::pivString;
if (s == "pistringlist" || s == "stringlist" || s == "vector<string>" || s == "vector<pistring>" || s == "pivector<string>" ||
s == "pivector<pistring>")
s == "pivector<pistring>")
return PIVariant::pivStringList;
if (s == "pitime" || s == "time") return PIVariant::pivTime;
if (s == "pidate" || s == "date") return PIVariant::pivDate;
@@ -1419,13 +1419,13 @@ PIString PIVariant::toString() const {
PIRectd r;
ba >> r;
return PIString::fromNumber(r.left()) + ";" + PIString::fromNumber(r.bottom()) + ";" + PIString::fromNumber(r.width()) + ";" +
PIString::fromNumber(r.height());
PIString::fromNumber(r.height());
} break;
case PIVariant::pivLine: {
PILined r;
ba >> r;
return PIString::fromNumber(r.p0.x) + ";" + PIString::fromNumber(r.p0.y) + ";" + PIString::fromNumber(r.p1.x) + ";" +
PIString::fromNumber(r.p1.y);
PIString::fromNumber(r.p1.y);
} break;
case PIVariant::pivCustom: return getAsValue<PIString>(*this);
default: break;

View File

@@ -5,22 +5,22 @@
* \~russian Вариативный тип
*/
/*
PIP - Platform Independent Primitives
Variant type
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Variant type
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIVARIANT_H
@@ -231,7 +231,7 @@ public:
//! \~russian Тип содержимого %PIVariant
enum Type {
pivInvalid /** \~english Invalid type, default type of empty contructor \~russian Недействительный тип, также конструированный по
умолчанию */
умолчанию */
= 0,
pivBool /** bool */,
pivChar /** char */,

View File

@@ -3,62 +3,75 @@
* \brief
* \~english Simple variant type
* \~russian Простой вариативный тип
*/
*/
/*
PIP - Platform Independent Primitives
Variant simple type
Ivan Pelipenko peri4ko@yandex.ru
PIP - Platform Independent Primitives
Variant simple type
Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIVARIANTSIMPLE_H
#define PIVARIANTSIMPLE_H
#include "pistring.h"
#include <typeinfo>
#ifdef MICRO_PIP
#include "pivariant.h"
# include "pivariant.h"
#endif
class __VariantFunctionsBase__ {
public:
virtual __VariantFunctionsBase__ * instance() {return 0;}
virtual PIString typeName() const {return PIString();}
virtual uint hash() const {return 0;}
virtual void newT(void *& ptr, const void * value) {;}
virtual void newNullT(void *& ptr) {;}
virtual void assignT(void *& ptr, const void * value) {;}
virtual void deleteT(void *& ptr) {;}
virtual __VariantFunctionsBase__ * instance() { return 0; }
virtual PIString typeName() const { return PIString(); }
virtual uint hash() const { return 0; }
virtual void newT(void *& ptr, const void * value) { ; }
virtual void newNullT(void *& ptr) { ; }
virtual void assignT(void *& ptr, const void * value) { ; }
virtual void deleteT(void *& ptr) { ; }
};
template<typename T>
class __VariantFunctions__: public __VariantFunctionsBase__ {
public:
__VariantFunctionsBase__ * instance() final {static __VariantFunctions__<T> ret; return &ret;}
__VariantFunctionsBase__ * instance() final {
static __VariantFunctions__<T> ret;
return &ret;
}
#ifdef MICRO_PIP
PIString typeName() const final {static PIString ret(PIVariant(T()).typeName()); return ret;}
PIString typeName() const final {
static PIString ret(PIVariant(T()).typeName());
return ret;
}
#else
PIString typeName() const final {static PIString ret(typeid(T).name()); return ret;}
PIString typeName() const final {
static PIString ret(typeid(T).name());
return ret;
}
#endif
uint hash() const final {static uint ret = typeName().hash(); return ret;}
void newT(void *& ptr, const void * value) final {ptr = (void*)(new T(*(const T*)value));}
void newNullT(void *& ptr) final {ptr = (void*)(new T());}
void assignT(void *& ptr, const void * value) final {*(T*)ptr = *(const T*)value;}
void deleteT(void *& ptr) final {delete (T*)(ptr);}
uint hash() const final {
static uint ret = typeName().hash();
return ret;
}
void newT(void *& ptr, const void * value) final { ptr = (void *)(new T(*(const T *)value)); }
void newNullT(void *& ptr) final { ptr = (void *)(new T()); }
void assignT(void *& ptr, const void * value) final { *(T *)ptr = *(const T *)value; }
void deleteT(void *& ptr) final { delete (T *)(ptr); }
};
@@ -77,34 +90,34 @@ public:
//! \}
class PIVariantSimple {
public:
//! \~english Construct null %PIVariantSimple
//! \~russian Создает пустой %PIVariantSimple
PIVariantSimple() {ptr = 0; f = 0;}
PIVariantSimple() {
ptr = 0;
f = 0;
}
//! \~english Contructs a copy of %PIVariantSimple.
//! \~russian Создает копию %PIVariantSimple.
PIVariantSimple(const PIVariantSimple & v) {
ptr = 0;
f = v.f;
if (f && v.ptr)
f->newT(ptr, v.ptr);
f = v.f;
if (f && v.ptr) f->newT(ptr, v.ptr);
}
~PIVariantSimple() {destroy();}
~PIVariantSimple() { destroy(); }
//! \~english Assign operator.
//! \~russian Оператор присваивания.
PIVariantSimple & operator=(const PIVariantSimple & v) {
destroy();
f = v.f;
if (f && v.ptr)
f->newT(ptr, v.ptr);
if (f && v.ptr) f->newT(ptr, v.ptr);
return *this;
}
//! \~english Set value to "v".
//! \~russian Устанавливает значение в "v".
template <typename T>
template<typename T>
void setValue(const T & v) {
if (f) {
if (isMyType<T>()) {
@@ -129,17 +142,16 @@ public:
//! В отличии от PIVariant этот класс строго проверяет типы.
//! Возвращает значение только если этот же тип был установлен ранее.
//!
template <typename T>
template<typename T>
T value() const {
if (!f) return T();
if (!isMyType<T>())
return T();
return *(T*)(ptr);
if (!isMyType<T>()) return T();
return *(T *)(ptr);
}
//! \~english Returns %PIVariantSimple with value "v".
//! \~russian Возвращает %PIVariantSimple со значением "v".
template <typename T>
template<typename T>
static PIVariantSimple fromValue(const T & v) {
PIVariantSimple ret;
ret.setValue(v);
@@ -147,7 +159,7 @@ public:
}
private:
template <typename T>
template<typename T>
bool isMyType() const {
if (!f) return false;
uint mh = f->hash(), th = __VariantFunctions__<T>().instance()->hash();
@@ -156,31 +168,46 @@ private:
}
void destroy() {
if (ptr && f)
f->deleteT(ptr);
if (ptr && f) f->deleteT(ptr);
ptr = 0;
f = 0;
f = 0;
}
void * ptr;
__VariantFunctionsBase__ * f;
};
#define REGISTER_PIVARIANTSIMPLE(Type) \
template<> \
#define REGISTER_PIVARIANTSIMPLE(Type) \
template<> \
class __VariantFunctions__<Type>: public __VariantFunctionsBase__ { \
public: \
__VariantFunctionsBase__ * instance() final {static __VariantFunctions__<Type> ret; return &ret;} \
PIString typeName() const final {static PIString ret(#Type); return ret;} \
uint hash() const final {static uint ret = typeName().hash(); return ret;} \
void newT(void *& ptr, const void * value) final {ptr = (void*)(new Type(*(const Type *)value));} \
void newNullT(void *& ptr) final {ptr = (void*)(new Type());} \
void assignT(void *& ptr, const void * value) final {*(Type *)ptr = *(const Type *)value;} \
void deleteT(void *& ptr) final {delete (Type *)(ptr);} \
public: \
__VariantFunctionsBase__ * instance() final { \
static __VariantFunctions__<Type> ret; \
return &ret; \
} \
PIString typeName() const final { \
static PIString ret(#Type); \
return ret; \
} \
uint hash() const final { \
static uint ret = typeName().hash(); \
return ret; \
} \
void newT(void *& ptr, const void * value) final { \
ptr = (void *)(new Type(*(const Type *)value)); \
} \
void newNullT(void *& ptr) final { \
ptr = (void *)(new Type()); \
} \
void assignT(void *& ptr, const void * value) final { \
*(Type *)ptr = *(const Type *)value; \
} \
void deleteT(void *& ptr) final { \
delete (Type *)(ptr); \
} \
};
REGISTER_PIVARIANTSIMPLE(std::function<void(void*)>)
REGISTER_PIVARIANTSIMPLE(std::function<void(void *)>)
#endif // PIVARIANTSIMPLE_H

View File

@@ -1,20 +1,20 @@
/*
PIP - Platform Independent Primitives
Variant types
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Variant types
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "pivarianttypes.h"

View File

@@ -3,24 +3,24 @@
* \brief
* \~english Types for PIVariant
* \~russian Типы для PIVariant
*/
*/
/*
PIP - Platform Independent Primitives
Variant types
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
PIP - Platform Independent Primitives
Variant types
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIVARIANTYPES_H
@@ -86,7 +86,7 @@ struct PIP_EXPORT Enum {
//! \~english Returns selected name.
//! \~russian Возвращает выбранное имя.
PIString selectedName() const {return selected;}
PIString selectedName() const { return selected; }
//! \~\brief
//! \~english Select value if exists in Enum.
@@ -136,19 +136,19 @@ struct PIP_EXPORT Enum {
//! \~english Add PIVariantTypes::Enumerator to Enum.
//! \~russian Добавляет в Enum PIVariantTypes::Enumerator.
Enum & operator <<(const Enumerator & v);
Enum & operator<<(const Enumerator & v);
//! \~english Add PIVariantTypes::Enumerator with name "v" and value of last element + 1, otherwise 0.
//! \~russian Добавляет PIVariantTypes::Enumerator с именем "v" и значением последнего элемента + 1, иначе 0.
Enum & operator <<(const PIString & v);
Enum & operator<<(const PIString & v);
//! \~english Add PIVariantTypes::Enumerator element for each name of vector.
//! \~russian Добавляет PIVariantTypes::Enumerator для каждой строки из массива.
Enum & operator <<(const PIStringList & v);
Enum & operator<<(const PIStringList & v);
//! \~english Returns if Enum is empty.
//! \~russian Возвращает пустой ли Enum.
bool isEmpty() const {return enum_list.isEmpty();}
bool isEmpty() const { return enum_list.isEmpty(); }
//! \~english Returns string full representation.
//! \~russian Возвращает полное строковое представление.
@@ -181,12 +181,15 @@ struct PIP_EXPORT Enum {
//! \~russian Описание положения файла.
//! \}
struct PIP_EXPORT File {
File(const PIString & p = PIString(), const PIString & f = PIString(), bool abs = false, bool save_mode = false):
file(p), filter(f), is_abs(abs), is_save(save_mode) {}
File(const PIString & p = PIString(), const PIString & f = PIString(), bool abs = false, bool save_mode = false)
: file(p)
, filter(f)
, is_abs(abs)
, is_save(save_mode) {}
//! \~english Returns path.
//! \~russian Возвращает путь.
PIString toString() const {return file;}
PIString toString() const { return file; }
//! \~english Path.
//! \~russian Путь.
@@ -214,12 +217,11 @@ struct PIP_EXPORT File {
//! \~russian Описание директории.
//! \}
struct PIP_EXPORT Dir {
Dir(const PIString & d = PIString(), bool abs = false):
dir(d), is_abs(abs) {}
Dir(const PIString & d = PIString(), bool abs = false): dir(d), is_abs(abs) {}
//! \~english Returns path.
//! \~russian Возвращает путь.
PIString toString() const {return dir;}
PIString toString() const { return dir; }
//! \~english Path.
//! \~russian Путь.
@@ -239,7 +241,7 @@ struct PIP_EXPORT Dir {
//! \~russian 32-битный цвет.
//! \}
struct PIP_EXPORT Color {
Color(uint v = 0) {rgba = v;}
Color(uint v = 0) { rgba = v; }
//! \~english Returns color from #HEX, 0xHEX or name.
//! \~russian Возвращает цвет от #HEX, 0xHEX или имени.
@@ -258,10 +260,18 @@ struct PIP_EXPORT Color {
uint rgba;
};
inline bool operator < (const Color c0, const Color c1) {return c0.rgba < c1.rgba;}
inline bool operator > (const Color c0, const Color c1) {return c0.rgba > c1.rgba;}
inline bool operator ==(const Color c0, const Color c1) {return c0.rgba == c1.rgba;}
inline bool operator !=(const Color c0, const Color c1) {return c0.rgba != c1.rgba;}
inline bool operator<(const Color c0, const Color c1) {
return c0.rgba < c1.rgba;
}
inline bool operator>(const Color c0, const Color c1) {
return c0.rgba > c1.rgba;
}
inline bool operator==(const Color c0, const Color c1) {
return c0.rgba == c1.rgba;
}
inline bool operator!=(const Color c0, const Color c1) {
return c0.rgba != c1.rgba;
}
//! \addtogroup Types
@@ -301,104 +311,163 @@ struct PIP_EXPORT IODevice {
PIByteArray props;
};
} // namespace PIVariantTypes
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator<<(PICout s, const PIVariantTypes::Enumerator & v) {
s << v.name << "(" << v.value << ")";
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator<<(PICout s, const PIVariantTypes::Enum & v) {
s << "Enum(" << v.selectedValue() << "=" << v.selectedName() << ")";
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator<<(PICout s, const PIVariantTypes::File & v) {
s << "File(\"" << v.file << "\")";
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator<<(PICout s, const PIVariantTypes::Dir & v) {
s << "Dir(\"" << v.dir << "\")";
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator<<(PICout s, const PIVariantTypes::Color & v) {
s.saveControls();
s << PICoutManipulators::Hex << "Color(#" << v.rgba << ")";
s.restoreControls();
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator<<(PICout s, const PIVariantTypes::IODevice & v) {
s << v.toPICout();
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIVariantTypes::Enumerator & v) {s << v.name << "(" << v.value << ")"; return s;}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::Enumerator) {
s << v.value << v.name;
return s;
}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIVariantTypes::Enum & v) {s << "Enum(" << v.selectedValue() << "=" << v.selectedName() << ")"; return s;}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIVariantTypes::File & v) {s << "File(\"" << v.file << "\")"; return s;}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIVariantTypes::Dir & v) {s << "Dir(\"" << v.dir << "\")"; return s;}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIVariantTypes::Color & v) {s.saveControls(); s << PICoutManipulators::Hex << "Color(#" << v.rgba << ")"; s.restoreControls(); return s;}
//! \relatesalso PICout
//! \~english Output operator to \a PICout
//! \~russian Оператор вывода в \a PICout
inline PICout operator <<(PICout s, const PIVariantTypes::IODevice & v) {s << v.toPICout(); return s;}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ(PIVariantTypes::Enumerator) {
s >> v.value >> v.name;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::Enumerator) {s << v.value << v.name; return s;}
BINARY_STREAM_WRITE(PIVariantTypes::Enum) {
s << v.enum_name << v.selected << v.enum_list;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIVariantTypes::Enumerator) {s >> v.value >> v.name; return s;}
BINARY_STREAM_READ(PIVariantTypes::Enum) {
s >> v.enum_name >> v.selected >> v.enum_list;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::Enum) {s << v.enum_name << v.selected << v.enum_list; return s;}
BINARY_STREAM_WRITE(PIVariantTypes::File) {
s << v.file << v.filter << uchar((v.is_abs ? 1 : 0) + (v.is_save ? 2 : 0));
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIVariantTypes::Enum) {s >> v.enum_name >> v.selected >> v.enum_list; return s;}
BINARY_STREAM_READ(PIVariantTypes::File) {
uchar f(0);
s >> v.file >> v.filter >> f;
v.is_abs = ((f & 1) == 1);
v.is_save = ((f & 2) == 2);
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::File) {s << v.file << v.filter << uchar((v.is_abs ? 1 : 0) + (v.is_save ? 2 : 0)); return s;}
BINARY_STREAM_WRITE(PIVariantTypes::Dir) {
s << v.dir << v.is_abs;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIVariantTypes::File) {uchar f(0); s >> v.file >> v.filter >> f; v.is_abs = ((f & 1) == 1); v.is_save = ((f & 2) == 2); return s;}
BINARY_STREAM_READ(PIVariantTypes::Dir) {
s >> v.dir >> v.is_abs;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::Dir) {s << v.dir << v.is_abs; return s;}
BINARY_STREAM_WRITE(PIVariantTypes::Color) {
s << v.rgba;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIVariantTypes::Dir) {s >> v.dir >> v.is_abs; return s;}
BINARY_STREAM_READ(PIVariantTypes::Color) {
s >> v.rgba;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::Color) {s << v.rgba; return s;}
BINARY_STREAM_WRITE(PIVariantTypes::IODevice) {
s << v.prefix << v.mode << v.options << v.props;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIVariantTypes::Color) {s >> v.rgba; return s;}
//! \relatesalso PIBinaryStream
//! \~english Store operator.
//! \~russian Оператор сохранения.
BINARY_STREAM_WRITE(PIVariantTypes::IODevice) {s << v.prefix << v.mode << v.options << v.props; return s;}
//! \relatesalso PIBinaryStream
//! \~english Restore operator.
//! \~russian Оператор извлечения.
BINARY_STREAM_READ (PIVariantTypes::IODevice) {s >> v.prefix >> v.mode >> v.options >> v.props; return s;}
BINARY_STREAM_READ(PIVariantTypes::IODevice) {
s >> v.prefix >> v.mode >> v.options >> v.props;
return s;
}
#endif // PIVARIANTYPES_H