From dc6fbbf7ec2ddb49da68aec1d0c687336beada99 Mon Sep 17 00:00:00 2001 From: peri4 Date: Fri, 25 Nov 2022 21:35:39 +0300 Subject: [PATCH] folders --- .../{core => serialization}/pibinarystream.h | 4 +- .../{core => serialization}/pichunkstream.cpp | 0 .../{core => serialization}/pichunkstream.h | 4 +- libs/main/{core => serialization}/pijson.cpp | 0 libs/main/{core => serialization}/pijson.h | 4 +- .../serialization/piserializationmodule.h | 58 + libs/main/{core => text}/pichar.cpp | 0 libs/main/{core => text}/pichar.h | 4 +- libs/main/{core => text}/piconstchars.cpp | 0 libs/main/{core => text}/piconstchars.h | 4 +- libs/main/{core => text}/pistring.cpp | 0 libs/main/{core => text}/pistring.h | 4 +- libs/main/{core => text}/pistring_std.h | 2 +- libs/main/{core => text}/pistringlist.cpp | 0 libs/main/{core => text}/pistringlist.h | 4 +- libs/main/text/pitextmodule.h | 58 + libs/main/{core => text}/pitextstream.h | 4 +- libs/main/{core => types}/pibitarray.cpp | 0 libs/main/{core => types}/pibitarray.h | 2 +- libs/main/{core => types}/pibytearray.cpp | 0 libs/main/{core => types}/pibytearray.h | 2544 ++++++++--------- libs/main/{core => types}/pidatetime.cpp | 2 +- libs/main/{core => types}/pidatetime.h | 8 +- libs/main/{core => types}/piflags.h | 4 +- .../{core => types}/pipropertystorage.cpp | 0 libs/main/{core => types}/pipropertystorage.h | 6 +- libs/main/{core => types}/pisystemtime.cpp | 0 libs/main/{core => types}/pisystemtime.h | 6 +- libs/main/{core => types}/pitime.cpp | 0 libs/main/{core => types}/pitime.h | 10 +- libs/main/{core => types}/pitime_win.h | 2 +- libs/main/types/pitypesmodule.h | 61 + libs/main/{core => types}/pivariant.cpp | 0 libs/main/{core => types}/pivariant.h | 4 +- libs/main/{core => types}/pivariantsimple.h | 4 +- libs/main/{core => types}/pivarianttypes.cpp | 0 libs/main/{core => types}/pivarianttypes.h | 16 +- 37 files changed, 1498 insertions(+), 1321 deletions(-) rename libs/main/{core => serialization}/pibinarystream.h (99%) rename libs/main/{core => serialization}/pichunkstream.cpp (100%) rename libs/main/{core => serialization}/pichunkstream.h (99%) rename libs/main/{core => serialization}/pijson.cpp (100%) rename libs/main/{core => serialization}/pijson.h (99%) create mode 100644 libs/main/serialization/piserializationmodule.h rename libs/main/{core => text}/pichar.cpp (100%) rename libs/main/{core => text}/pichar.h (99%) rename libs/main/{core => text}/piconstchars.cpp (100%) rename libs/main/{core => text}/piconstchars.h (99%) rename libs/main/{core => text}/pistring.cpp (100%) rename libs/main/{core => text}/pistring.h (99%) rename libs/main/{core => text}/pistring_std.h (99%) rename libs/main/{core => text}/pistringlist.cpp (100%) rename libs/main/{core => text}/pistringlist.h (99%) create mode 100644 libs/main/text/pitextmodule.h rename libs/main/{core => text}/pitextstream.h (99%) rename libs/main/{core => types}/pibitarray.cpp (100%) rename libs/main/{core => types}/pibitarray.h (99%) rename libs/main/{core => types}/pibytearray.cpp (100%) rename libs/main/{core => types}/pibytearray.h (98%) rename libs/main/{core => types}/pidatetime.cpp (99%) rename libs/main/{core => types}/pidatetime.h (99%) rename libs/main/{core => types}/piflags.h (99%) rename libs/main/{core => types}/pipropertystorage.cpp (100%) rename libs/main/{core => types}/pipropertystorage.h (99%) rename libs/main/{core => types}/pisystemtime.cpp (100%) rename libs/main/{core => types}/pisystemtime.h (99%) rename libs/main/{core => types}/pitime.cpp (100%) rename libs/main/{core => types}/pitime.h (95%) rename libs/main/{core => types}/pitime_win.h (99%) create mode 100644 libs/main/types/pitypesmodule.h rename libs/main/{core => types}/pivariant.cpp (100%) rename libs/main/{core => types}/pivariant.h (99%) rename libs/main/{core => types}/pivariantsimple.h (99%) rename libs/main/{core => types}/pivarianttypes.cpp (100%) rename libs/main/{core => types}/pivarianttypes.h (98%) diff --git a/libs/main/core/pibinarystream.h b/libs/main/serialization/pibinarystream.h similarity index 99% rename from libs/main/core/pibinarystream.h rename to libs/main/serialization/pibinarystream.h index cf9e184a..676667ff 100644 --- a/libs/main/core/pibinarystream.h +++ b/libs/main/serialization/pibinarystream.h @@ -1,5 +1,5 @@ /*! \file pibinarystream.h - * \ingroup Core + * \ingroup Serialization * \~\brief * \~english Binary serialization interface * \~russian Интерфейс бинарной сериализации @@ -42,7 +42,7 @@ template inline PIBinaryStream

& operator >>(PIBinaryStream

& s, T & v) -//! \ingroup Core +//! \ingroup Serialization //! \~\brief //! \~english Binary serialization interface. //! \~russian Интерфейс бинарной сериализации. diff --git a/libs/main/core/pichunkstream.cpp b/libs/main/serialization/pichunkstream.cpp similarity index 100% rename from libs/main/core/pichunkstream.cpp rename to libs/main/serialization/pichunkstream.cpp diff --git a/libs/main/core/pichunkstream.h b/libs/main/serialization/pichunkstream.h similarity index 99% rename from libs/main/core/pichunkstream.h rename to libs/main/serialization/pichunkstream.h index 68493586..d3ec67eb 100644 --- a/libs/main/core/pichunkstream.h +++ b/libs/main/serialization/pichunkstream.h @@ -1,5 +1,5 @@ /*! \file pichunkstream.h - * \ingroup Core + * \ingroup Serialization * \~\brief * \~english Binary markup de/serializator stream * \~russian Бинарный поток для де/сериализации с разметкой @@ -29,7 +29,7 @@ #include "pibytearray.h" -//! \ingroup Core +//! \ingroup Serialization //! \~\brief //! \~english Class for binary de/serialization. //! \~russian Класс для бинарной де/сериализации. diff --git a/libs/main/core/pijson.cpp b/libs/main/serialization/pijson.cpp similarity index 100% rename from libs/main/core/pijson.cpp rename to libs/main/serialization/pijson.cpp diff --git a/libs/main/core/pijson.h b/libs/main/serialization/pijson.h similarity index 99% rename from libs/main/core/pijson.h rename to libs/main/serialization/pijson.h index 8b3e4528..b449a5b7 100644 --- a/libs/main/core/pijson.h +++ b/libs/main/serialization/pijson.h @@ -1,5 +1,5 @@ /*! \file pijson.h - * \ingroup Core + * \ingroup Serialization * \brief * \~english JSON class * \~russian Класс JSON @@ -29,7 +29,7 @@ #include "pivariant.h" -//! \ingroup Core +//! \ingroup Serialization //! \~\brief //! \~english JSON class. //! \~russian Класс JSON. diff --git a/libs/main/serialization/piserializationmodule.h b/libs/main/serialization/piserializationmodule.h new file mode 100644 index 00000000..4f5b970a --- /dev/null +++ b/libs/main/serialization/piserializationmodule.h @@ -0,0 +1,58 @@ +/* + 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 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 . +*/ +//! \defgroup Serialization Serialization +//! \~\brief +//! \~english Serialization. +//! \~russian Сериализация. +//! +//! \~\details +//! \~english \section cmake_module_Serialization Building with CMake +//! \~russian \section cmake_module_Serialization Сборка с использованием CMake +//! +//! \~\code +//! find_package(PIP REQUIRED) +//! target_link_libraries([target] PIP) +//! \endcode +//! +//! \~english \par Common +//! \~russian \par Общее +//! +//! \~english +//! +//! +//! \~russian +//! +//! +//! \~\authors +//! \~english +//! Ivan Pelipenko peri4ko@yandex.ru; +//! Andrey Bychkov work.a.b@yandex.ru; +//! \~russian +//! Иван Пелипенко peri4ko@yandex.ru; +//! Андрей Бычков work.a.b@yandex.ru; +//! + +#ifndef PISERIALIZATIONMODULE_H +#define PISERIALIZATIONMODULE_H + +#include "pibinarystream.h" +#include "pichunkstream.h" +#include "pijson.h" + +#endif // PISERIALIZATIONMODULE_H diff --git a/libs/main/core/pichar.cpp b/libs/main/text/pichar.cpp similarity index 100% rename from libs/main/core/pichar.cpp rename to libs/main/text/pichar.cpp diff --git a/libs/main/core/pichar.h b/libs/main/text/pichar.h similarity index 99% rename from libs/main/core/pichar.h rename to libs/main/text/pichar.h index 2accf07f..1be525d0 100644 --- a/libs/main/core/pichar.h +++ b/libs/main/text/pichar.h @@ -1,5 +1,5 @@ /*! \file pichar.h - * \ingroup Core + * \ingroup Text * \~\brief * \~english Single string character * \~russian Один символ строки @@ -32,7 +32,7 @@ extern PIP_EXPORT char * __syslocname__; extern PIP_EXPORT char * __sysoemname__; extern PIP_EXPORT char * __utf8name__; -//! \ingroup Core +//! \ingroup Text //! \~\brief //! \~english %PIChar represents a single character. //! \~russian %PIChar представляет собой один символ строки. diff --git a/libs/main/core/piconstchars.cpp b/libs/main/text/piconstchars.cpp similarity index 100% rename from libs/main/core/piconstchars.cpp rename to libs/main/text/piconstchars.cpp diff --git a/libs/main/core/piconstchars.h b/libs/main/text/piconstchars.h similarity index 99% rename from libs/main/core/piconstchars.h rename to libs/main/text/piconstchars.h index 1a00bfd6..e99d861c 100644 --- a/libs/main/core/piconstchars.h +++ b/libs/main/text/piconstchars.h @@ -1,5 +1,5 @@ /*! \file piconstchars.h - * \ingroup Core + * \ingroup Text * \brief * \~english C-String class * \~russian Класс C-строки @@ -29,7 +29,7 @@ #include "picout.h" -//! \ingroup Core +//! \ingroup Text //! \~\brief //! \~english C-String class. //! \~russian Класс C-строки. diff --git a/libs/main/core/pistring.cpp b/libs/main/text/pistring.cpp similarity index 100% rename from libs/main/core/pistring.cpp rename to libs/main/text/pistring.cpp diff --git a/libs/main/core/pistring.h b/libs/main/text/pistring.h similarity index 99% rename from libs/main/core/pistring.h rename to libs/main/text/pistring.h index 7b71b7be..502dc4a3 100644 --- a/libs/main/core/pistring.h +++ b/libs/main/text/pistring.h @@ -1,5 +1,5 @@ /*! \file pistring.h - * \ingroup Core + * \ingroup Text * \brief * \~english String class * \~russian Класс строки @@ -34,7 +34,7 @@ class PIStringList; -//! \ingroup Core +//! \ingroup Text //! \~\brief //! \~english String class. //! \~russian Класс строки. diff --git a/libs/main/core/pistring_std.h b/libs/main/text/pistring_std.h similarity index 99% rename from libs/main/core/pistring_std.h rename to libs/main/text/pistring_std.h index 8bf649ab..36f6847d 100644 --- a/libs/main/core/pistring_std.h +++ b/libs/main/text/pistring_std.h @@ -1,5 +1,5 @@ /*! \file pistring_std.h - * \ingroup Core + * \ingroup Text * \brief * \~english STD convertions for PIString * \~russian Преобразования в/из STD для строки diff --git a/libs/main/core/pistringlist.cpp b/libs/main/text/pistringlist.cpp similarity index 100% rename from libs/main/core/pistringlist.cpp rename to libs/main/text/pistringlist.cpp diff --git a/libs/main/core/pistringlist.h b/libs/main/text/pistringlist.h similarity index 99% rename from libs/main/core/pistringlist.h rename to libs/main/text/pistringlist.h index dc8abc32..4df6fa51 100644 --- a/libs/main/core/pistringlist.h +++ b/libs/main/text/pistringlist.h @@ -1,5 +1,5 @@ /*! \file pistringlist.h - * \ingroup Core + * \ingroup Text * \~\brief * \~english Based on \a PIDeque strings list * \~russian Основанный на \a PIDeque массив строк @@ -29,7 +29,7 @@ #include "pistring.h" -//! \ingroup Core +//! \ingroup Text //! \~\brief //! \~english Based on \a PIDeque strings list. //! \~russian Основанный на \a PIDeque массив строк. diff --git a/libs/main/text/pitextmodule.h b/libs/main/text/pitextmodule.h new file mode 100644 index 00000000..ca811e86 --- /dev/null +++ b/libs/main/text/pitextmodule.h @@ -0,0 +1,58 @@ +/* + 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 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 . +*/ +//! \defgroup Text Text +//! \~\brief +//! \~english String classes. +//! \~russian Классы строк. +//! +//! \~\details +//! \~english \section cmake_module_Text Building with CMake +//! \~russian \section cmake_module_Text Сборка с использованием CMake +//! +//! \~\code +//! find_package(PIP REQUIRED) +//! target_link_libraries([target] PIP) +//! \endcode +//! +//! \~english \par Common +//! \~russian \par Общее +//! +//! \~english +//! +//! +//! \~russian +//! +//! +//! \~\authors +//! \~english +//! Ivan Pelipenko peri4ko@yandex.ru; +//! Andrey Bychkov work.a.b@yandex.ru; +//! \~russian +//! Иван Пелипенко peri4ko@yandex.ru; +//! Андрей Бычков work.a.b@yandex.ru; +//! + +#ifndef PITEXTMODULE_H +#define PITEXTMODULE_H + +#include "pistringlist.h" +#include "piconstchars.h" +#include "pitextstream.h" + +#endif // PITEXTMODULE_H diff --git a/libs/main/core/pitextstream.h b/libs/main/text/pitextstream.h similarity index 99% rename from libs/main/core/pitextstream.h rename to libs/main/text/pitextstream.h index e0a074cc..d39e96cd 100644 --- a/libs/main/core/pitextstream.h +++ b/libs/main/text/pitextstream.h @@ -1,5 +1,5 @@ /*! \file pitextstream.h - * \ingroup Core + * \ingroup Text * \~\brief * \~english Text serialization functionality over PIBinaryStream * \~russian Функциональность текстовой сериализации поверх PIBinaryStream @@ -29,7 +29,7 @@ #include "pistring.h" -//! \ingroup Core +//! \ingroup Text //! \~\brief //! \~english Text serialization functionality over PIBinaryStream. //! \~russian Функциональность текстовой сериализации поверх PIBinaryStream. diff --git a/libs/main/core/pibitarray.cpp b/libs/main/types/pibitarray.cpp similarity index 100% rename from libs/main/core/pibitarray.cpp rename to libs/main/types/pibitarray.cpp diff --git a/libs/main/core/pibitarray.h b/libs/main/types/pibitarray.h similarity index 99% rename from libs/main/core/pibitarray.h rename to libs/main/types/pibitarray.h index 00e36804..af0b0e5a 100644 --- a/libs/main/core/pibitarray.h +++ b/libs/main/types/pibitarray.h @@ -28,7 +28,7 @@ #include "pivector.h" -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english The %PIBitArray class provides an space-efficient array of bits. //! \~russian Класс %PIBitArray представляет собой компактный массив битов. diff --git a/libs/main/core/pibytearray.cpp b/libs/main/types/pibytearray.cpp similarity index 100% rename from libs/main/core/pibytearray.cpp rename to libs/main/types/pibytearray.cpp diff --git a/libs/main/core/pibytearray.h b/libs/main/types/pibytearray.h similarity index 98% rename from libs/main/core/pibytearray.h rename to libs/main/types/pibytearray.h index 301cce65..6ce8830e 100644 --- a/libs/main/core/pibytearray.h +++ b/libs/main/types/pibytearray.h @@ -1,1272 +1,1272 @@ -/*! \file pibytearray.h - * \ingroup Core - * \~\brief - * \~english Byte array - * \~russian Байтовый массив -*/ -/* - 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 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 . -*/ - -#ifndef PIBYTEARRAY_H -#define PIBYTEARRAY_H - -#include "pichar.h" -#include "pibinarystream.h" -#include - -class PIString; -class PIByteArray; - - -//! \ingroup Core -//! \~\brief -//! \~english The %PIByteArray class provides an array of bytes. -//! \~russian Класс %PIByteArray представляет собой массив байтов. -class PIP_EXPORT PIByteArray: public PIBinaryStream -{ -public: - typedef ::PIMemoryBlock RawData DEPRECATEDM("use PIMemoryBlock instead"); - - //! \~english Constructs an empty byte array - //! \~russian Создает пустой байтовый массив - PIByteArray() {} - - //! \~english Constructs copy of byte array "o" - //! \~russian Создает копию байтового массива "o" - PIByteArray(const PIByteArray & o): d(o.d) {} - - //! \~english Constructs copy of byte array "o" - //! \~russian Создает копию байтового массива "o" - PIByteArray(const PIDeque & o): d(o) {} - - PIByteArray(PIByteArray && o): d(std::move(o.d)) {} - - //! \~english Constructs 0-filled byte array with size "size" - //! \~russian Создает заполненный "0" байтовый массив размером "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)) {} - - //! \~english Constructs byte array with size "size" filled by "t" - //! \~russian Создает заполненный "t" байтовый массив размером "size" - PIByteArray(const uint size, uchar t): d(size, t) {} - - //! \~english Contructs array from - //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). - //! \~russian Создает массив из - //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). - //! \~\details - //! \~\code - //! PIByteArray v{1,2,3}; - //! piCout << v; // {1, 2, 3} - //! \endcode - PIByteArray(std::initializer_list 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); - } - - //! \~english Iterator to the first element. - //! \~russian Итератор на первый элемент. - //! \~\details ![begin, end](doc/images/pivector_begin.png) - //! - //! \~english If the array is empty, the returned iterator is equal to \a end(). - //! \~russian Если массив - пуст, возвращаемый итератор будет равен \a end(). - //! \~\return \ref stl_iterators - //! \~\sa \a end(), \a rbegin(), \a rend() - inline PIDeque::iterator begin() {return d.begin();} - - //! \~english Iterator to the element following the last element. - //! \~russian Итератор на элемент, следующий за последним элементом. - //! \~\details ![begin, end](doc/images/pivector_begin.png) - //! - //! \~english This element acts as a placeholder; - //! attempting to access it results in undefined behavior. - //! \~russian Этот элемент существует лишь условно, - //! попытка доступа к нему приведёт к выходу за разрешенную память. - //! \~\return \ref stl_iterators - //! \~\sa \a begin(), \a rbegin(), \a rend() - inline PIDeque::iterator end() {return d.end();} - - inline PIDeque::const_iterator begin() const {return d.begin();} - inline PIDeque::const_iterator end() const {return d.end();} - - //! \~english Returns a reverse iterator to the first element of the reversed array. - //! \~russian Обратный итератор на первый элемент. - //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) - //! - //! \~english It corresponds to the last element of the non-reversed array. - //! If the array is empty, the returned iterator is equal to \a rend(). - //! \~russian Итератор для прохода массива в обратном порядке. - //! Указывает на последний элемент. - //! Если массив пустой, то совпадает с итератором \a rend(). - //! \~\return \ref stl_iterators - //! \~\sa \a rend(), \a begin(), \a end() - inline PIDeque::reverse_iterator rbegin() {return d.rbegin();} - - //! \~english Returns a reverse iterator to the element. - //! following the last element of the reversed array. - //! \~russian Обратный итератор на элемент, следующий за последним элементом. - //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) - //! - //! \~english It corresponds to the element preceding the first element of the non-reversed array. - //! This element acts as a placeholder, attempting to access it results in undefined behavior. - //! \~russian Итератор для прохода массива в обратном порядке. - //! Указывает на элемент, предшествующий первому элементу. - //! Этот элемент существует лишь условно, - //! попытка доступа к нему приведёт к выходу за разрешенную память. - //! \~\return \ref stl_iterators - //! \~\sa \a rbegin(), \a begin(), \a end() - inline PIDeque::reverse_iterator rend() {return d.rend();} - - inline PIDeque::const_reverse_iterator rbegin() const {return d.rbegin();} - inline PIDeque::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();} - - //! \~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();} - - //! \~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();} - - //! \~english Number of elements that the container has currently allocated space for. - //! \~russian Количество элементов, для которого сейчас выделена память массивом. - //! \~\details - //! \~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();} - - //! \~english Checks if the container has no elements. - //! \~russian Проверяет пуст ли массив. - //! \~\return - //! \~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();} - - //! \~english Checks if the container has elements. - //! \~russian Проверяет не пуст ли массив. - //! \~\return - //! \~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();} - - //! \~english Tests whether at least one element in the array - //! passes the test implemented by the provided function `test`. - //! \~russian Проверяет, удовлетворяет ли какой-либо элемент массива условию, - //! заданному в передаваемой функции `test`. - //! \~\return - //! \~english **true** if, in the array, - //! it finds an element for which the provided function returns **true**; - //! otherwise it returns **false**. Always returns **false** if is empty. - //! \~russian **true** если хотя бы для одного элемента - //! передаваемая функция возвращает **true**, в остальных случаях **false**. - //! Метод возвращает **false** при любом условии для пустого массива. - //! \~\details - //! \~\sa \a every(), \a contains(), \a entries(), \a forEach() - inline bool any(std::function test) const { - return d.any(test); - } - - //! \~english Tests whether all elements in the array passes the test - //! implemented by the provided function `test`. - //! \~russian Проверяет, удовлетворяют ли все элементы массива условию, - //! заданному в передаваемой функции `test`. - //! \~\return - //! \~english **true** if, in the array, - //! it finds an element for which the provided function returns **true**; - //! otherwise it returns **false**. Always returns **true** if is empty. - //! \~russian **true** если для всех элементов передаваемая функция возвращает **true**, - //! в остальных случаях **false**. - //! Метод возвращает **true** при любом условии для пустого массива. - //! \~\details - //! \~\sa \a any(), \a contains(), \a entries(), \a forEach() - inline bool every(std::function test) const { - return d.every(test); - } - - //! \~english Full access to element by `index`. - //! \~russian Полный доступ к элементу по индексу `index`. - //! \~\details - //! \~english Element index starts from `0`. - //! Element index must be in range from `0` to `size()-1`. - //! Otherwise will be undefined behavior. - //! \~russian Индекс элемента считается от `0`. - //! Индекс элемента должен лежать в пределах от `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];} - - //! \~english Read only access to element by `index`. - //! \~russian Доступ исключительно на чтение к элементу по индексу `index`. - //! \~\details - //! \~english Element index starts from `0`. - //! Element index must be in range from `0` to `size()-1`. - //! Otherwise will be undefined behavior. - //! \~russian Индекс элемента считается от `0`. - //! Индекс элемента должен лежать в пределах от `0` до `size()-1`. - //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. - inline uchar at(size_t index) const {return d.at(index);} - - //! \~english Last element. - //! \~russian Последний элемент массива. - //! \~\details - //! \~english Returns a reference to the last item in the array. - //! This function assumes that the array isn't empty. - //! Otherwise will be undefined behavior. - //! \~russian Возвращает ссылку на последний элемент в массиве. - //! Эта функция предполагает, что массив не пустой. - //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. - inline uchar & back() {return d.back();} - inline uchar back() const {return d.back();} - - //! \~english Last element. - //! \~russian Первый элемент массива. - //! \~\details - //! \~english Returns a reference to the last item in the array. - //! This function assumes that the array isn't empty. - //! Otherwise will be undefined behavior. - //! \~russian Возвращает ссылку на пенрвый элемент в массиве. - //! Эта функция предполагает, что массив не пустой. - //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. - inline uchar & front() {return d.front();} - inline uchar front() const {return d.front();} - - //! \~english Tests if element `e` exists in the array. - //! \~russian Проверяет наличие элемента `e` в массиве. - //! \~\details - //! \~english Optional argument `start` - the position in this array at which to begin searching. - //! If the index is greater than or equal to the array's size, - //! **false** is returned, which means the array will not be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Note: if the provided index is negative, - //! the array is still searched from front to back. - //! Default: 0 (entire array is searched). - //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. - //! Если индекс больше или равен длине массива, - //! возвращается **false**, что означает, что массив даже не просматривается. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. - //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. - //! \~\code - //! PIByteArray v{1, 2, 3, 4}; - //! piCout << v.contains(3); // true - //! piCout << v.contains(5); // false - //! piCout << v.contains(3, 3); // false - //! piCout << v.contains(3, -2); // true - //! piCout << v.contains(3, -99); // true - //! \endcode - //! \~\return - //! \~english **true** if the array contains an occurrence of element `e`, - //! otherwise it returns **false**. - //! \~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); - } - - //! \~english Count elements equal `e` in the array. - //! \~russian Подсчитывает количество элементов, совпадающих с элементом `e` в массиве. - //! \~\details - //! \~english Optional argument `start` - the position in this array at which to begin searching. - //! If the index is greater than or equal to the array's size, - //! 0 is returned, which means the array will not be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Note: if the provided index is negative, - //! the array is still searched from front to back. - //! Default: 0 (entire array is searched). - //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. - //! Если индекс больше или равен длине массива, - //! возвращается 0, что означает, что массив даже не просматривается. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. - //! Значение по умолчанию равно 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); - } - - //! \~english Count elements in the array passes the test implemented by the provided function `test`. - //! \~russian Подсчитывает количество элементов в массиве, - //! проходящих по условию, заданному в передаваемой функции `test`. - //! \~\details - //! \~english Overloaded function. - //! Optional argument `start` - the position in this array at which to begin searching. - //! If the index is greater than or equal to the array's size, - //! 0 is returned, which means the array will not be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Note: if the provided index is negative, - //! the array is still searched from front to back. - //! Default: 0 (entire array is searched). - //! \~russian Перегруженная функция. - //! Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. - //! Если индекс больше или равен длине массива, - //! возвращается 0, что означает, что массив даже не просматривается. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. - //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. - //! \~\sa \a every(), \a any(), \a contains(), \a indexWhere() - inline int entries(std::function 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. - //! \~russian Возвращает первый индекс, по которому данный элемент `e` - //! может быть найден в массиве или `-1`, если такого индекса нет. - //! \~\details - //! \~english Optional argument `start` - the position in this array at which to begin searching. - //! If the index is greater than or equal to the array's size, - //! `-1` is returned, which means the array will not be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Note: if the provided index is negative, - //! the array is still searched from front to back. - //! Default: 0 (entire array is searched). - //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. - //! Если индекс больше или равен длине массива, - //! возвращается `-1`, что означает, что массив даже не просматривается. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. - //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. - //! \~\code - //! PIByteArray v{2, 5, 9}; - //! piCout << v.indexOf(2); // 0 - //! piCout << v.indexOf(7); // -1 - //! piCout << v.indexOf(9, 2); // 2 - //! piCout << v.indexOf(2, -1); // -1 - //! 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); - } - - //! \~english Returns the first index passes the test implemented by the provided function `test`, - //! or `-1` if it is not present. - //! can be found in the array, or `-1` if it is not present. - //! \~russian Возвращает первый индекс элемента проходящего по условию, - //! заданному в передаваемой функции `test`, или `-1`, если таких элементов нет. - //! \~\details - //! \~english Optional argument `start` - the position in this array at which to begin searching. - //! If the index is greater than or equal to the array's size, - //! `-1` is returned, which means the array will not be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Note: if the provided index is negative, - //! the array is still searched from front to back. - //! Default: 0 (entire array is searched). - //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. - //! Если индекс больше или равен длине массива, - //! возвращается `-1`, что означает, что массив даже не просматривается. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. - //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. - //! \~\code - //! PIByteArray v{2, 5, 9}; - //! piCout << v.indexWhere([](const uchar & s){return s > 3;}); // 1 - //! piCout << v.indexWhere([](const uchar & s){return s > 3;}, 2); // 2 - //! 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 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. - //! \~russian Возвращает последний индекс, по которому данный элемент `e` - //! может быть найден в массиве или `-1`, если такого индекса нет. - //! \~\details - //! \~english Optional argument `start` - the position in this array - //! at which to start searching backwards. - //! If the index is greater than or equal to the array's size, - //! causes the whole array to be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Therefore, if calculated index less than 0, - //! the array is not searched, and the method returns `-1`. - //! Note: if the provided index is negative, - //! the array is still searched from back to front. - //! Default: -1 (entire array is searched). - //! \~russian Опциональный аргумент `start` указывает на индекс - //! c которого начинать поиск в обратном направлении. - //! Если индекс больше или равен длине массива, просматривается весь массив. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от конца к началу. - //! Если рассчитанный индекс оказывается меньше 0, массив даже не просматривается. - //! Значение по умолчанию равно `-1`, что равно индексу последнего элемента - //! и означает, что просматривается весь массив. - //! \~\code - //! PIByteArray v{2, 5, 9, 2}; - //! piCout << v.lastIndexOf(2); // 3 - //! piCout << v.lastIndexOf(7); // -1 - //! piCout << v.lastIndexOf(2, 2); // 0 - //! piCout << v.lastIndexOf(2, -3); // 0 - //! piCout << v.lastIndexOf(2, -300); // -1 - //! 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); - } - - //! \~english Returns the last index passes the test implemented by the provided function `test`, - //! or `-1` if it is not present. - //! \~russian Возвращает последний индекс элемента проходящего по условию, - //! заданному в передаваемой функции `test`, или `-1`, если таких элементов нет. - //! \~\details - //! \~english Optional argument `start` - the position in this array - //! at which to start searching backwards. - //! If the index is greater than or equal to the array's size, - //! causes the whole array to be searched. - //! If the provided index value is a negative number, - //! it is taken as the offset from the end of the array. - //! Therefore, if calculated index less than 0, - //! the array is not searched, and the method returns `-1`. - //! Note: if the provided index is negative, - //! the array is still searched from back to front. - //! Default: -1 (entire array is searched). - //! \~russian Опциональный аргумент `start` указывает на индекс - //! c которого начинать поиск в обратном направлении. - //! Если индекс больше или равен длине массива, просматривается весь массив. - //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. - //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от конца к началу. - //! Если рассчитанный индекс оказывается меньше 0, массив даже не просматривается. - //! Значение по умолчанию равно `-1`, что равно индексу последнего элемента - //! и означает, что просматривается весь массив. - //! \~\sa \a indexOf(), \a lastIndexOf(), \a indexWhere(), \a contains() - inline ssize_t lastIndexWhere(std::function test, ssize_t start = -1) const { - return d.lastIndexWhere(test, start); - } - - //! \~english Pointer to array - //! \~russian Указатель на память массива - //! \~\details - //! \~english Optional argument `index` the position in this array, - //! where is pointer. Default: start of array. - //! \~russian Опциональный аргумент `index` указывает на индекс c которого брать указатель. - //! По умолчанию указывает на начало массива. - inline uchar * data(size_t index = 0) {return d.data(index);} - - //! \~english Read only pointer to array - //! \~russian Указатель на память массива только для чтения. - //! \~\details - //! \~english The pointer can be used to access and modify the items in the array. - //! The pointer remains valid as long as the array isn't reallocated. - //! Optional argument `index` the position in this array, - //! where is pointer. Default: start of array. - //! \~russian Указатель можно использовать для доступа и изменения элементов в массиве. - //! Указатель остается действительным только до тех пор, пока массив не будет перераспределен. - //! Опциональный аргумент `index` указывает на индекс c которого брать указатель. - //! По умолчанию указывает на начало массива. - inline const uchar * data(size_t index = 0) const {return d.data(index);} - - //! \~english Clear array, remove all elements. - //! \~russian Очищает массив, удаляет все элементы. - //! \~\details - //! \~\note - //! \~english Reserved memory will not be released. - //! \~russian Зарезервированная память не освободится. - //! \~\sa \a resize() - inline PIByteArray & clear() { - resize(0); - return *this; - } - - //! \~english Assigns element 'e' to all items in the array. - //! \~russian Заполняет весь массив копиями элемента 'e'. - //! \~\details - //! \~\sa \a resize() - inline PIByteArray & fill(uchar e = 0) { - d.fill(e); - return *this; - } - - //! \~english Assigns result of function 'f(size_t i)' to all items in the array. - //! \~russian Заполняет весь массив результатом вызова функции 'f(size_t i)'. - //! \~\details - //! \~\sa \a resize() - inline PIByteArray & fill(std::function f) { - d.fill(f); - return *this; - } - - //! \~english Same as \a fill(). - //! \~russian Тоже самое что и \a fill(). - //! \~\sa \a fill(), \a resize() - inline PIByteArray & assign(uchar e = 0) {return fill(e);} - - //! \~english First does `resize(new_size)` then `fill(e)`. - //! \~russian Сначала делает `resize(new_size)`, затем `fill(e)`. - //! \~\sa \a fill(), \a resize() - inline PIByteArray & assign(size_t new_size, uchar e) { - resize(new_size); - return fill(e); - } - - //! \~english Sets size of the array, new elements are copied from `e`. - //! \~russian Устанавливает размер массива, новые элементы копируются из `e`. - //! \~\details - //! \~english If `new_size` is greater than the current \a size(), - //! elements are added to the end; the new elements are initialized from `e`. - //! If `new_size` is less than the current \a size(), elements are removed from the end. - //! \~russian Если `new_size` больше чем текущий размер массива \a size(), - //! новые элементы добавляются в конец массива и создаются из `e`. - //! Если `new_size` меньше чем текущий размер массива \a size(), - //! лишние элементы удаляются с конца массива. - //! \~\sa \a size(), \a clear() - inline PIByteArray & resize(size_t new_size, uchar e = 0) { - d.resize(new_size, e); - return *this; - } - - //! \~english Sets size of the array, new elements created by function `f(size_t i)`. - //! \~russian Устанавливает размер массива, новые элементы создаются функцией `f(size_t i)`. - //! \~\details - //! \~english If `new_size` is greater than the current \a size(), - //! elements are added to the end; the new elements created by function `f(size_t i)`. - //! If `new_size` is less than the current \a size(), elements are removed from the end. - //! \~russian Если `new_size` больше чем текущий размер массива \a size(), - //! новые элементы добавляются в конец массива и функцией `f(size_t i)`. - //! Если `new_size` меньше чем текущий размер массива \a size(), - //! лишние элементы удаляются с конца массива. - //! \~\sa \a size(), \a clear() - inline PIByteArray & resize(size_t new_size, std::function f) { - d.resize(new_size, f); - return *this; - } - - //! \~english Return resized byte array - //! \~russian Возвращает копию байтового массива с измененным размером - PIByteArray resized(uint new_size) const { - PIByteArray ret(new_size); - memcpy(ret.data(), data(), new_size); - return ret; - } - - //! \~english Attempts to allocate memory for at least `new_size` elements. - //! \~russian Резервируется память под как минимум `new_size` элементов. - //! \~\details - //! \~english If you know in advance how large the array will be, - //! you should call this function to prevent reallocations and memory fragmentation. - //! If `new_size` is greater than the current \a capacity(), - //! new storage is allocated, otherwise the function does nothing. - //! This function does not change the \a size() of the array. - //! \~russian Если вы заранее знаете, насколько велик будет массив, - //! вы можете вызвать эту функцию, чтобы предотвратить перераспределение и фрагментацию памяти. - //! Если размер `new_size` больше чем выделенная память \a capacity(), - //! то произойдёт выделение новой памяти и перераспределение массива. - //! Эта функция не изменяет количество элементов в массиве \a size(). - //! \~\sa \a size(), \a capacity(), \a resize() - inline PIByteArray & reserve(size_t new_size) { - d.reserve(new_size); - return *this; - } - - //! \~english Inserts value `e` at `index` position in the array. - //! \~russian Вставляет значение `e` в позицию `index` в массиве. - //! \~\details - //! \~english The index must be greater than 0 and less than or equal to \a size(). - //! \~russian Индекс должен быть больше 0 и меньше или равен \a size(). - //! \~\sa \a append(), \a prepend(), \a remove() - inline PIByteArray & insert(size_t index, uchar e = 0) { - d.insert(index, e); - return *this; - } - - //! \~english Inserts array `v` at `index` position in the array. - //! \~russian Вставляет массив `v` в позицию `index` в массиве. - //! \~\details - //! \~english The index must be greater than or equal to 0 and less than or equal to \a size(). - //! \~russian Индекс должен быть больше или равен 0 и меньше или равен \a size(). - //! \~\sa \a append(), \a prepend(), \a remove() - inline PIByteArray & insert(size_t index, const PIByteArray & v) { - d.insert(index, v.d); - return *this; - } - - //! \~english Inserts the given elements at `index` position in the array. - //! \~russian Вставляет элементы в позицию `index` в массиве. - //! \~\details - //! \~english The index must be greater than or equal to 0 and less than or equal to \a size(). - //! Inserts the given elements from - //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). - //! \~russian Индекс должен быть больше или равен 0 и меньше или равен \a size(). - //! Вставляет элементы из - //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). - //! \~\sa \a append(), \a prepend(), \a remove() - inline PIByteArray & insert(size_t index, std::initializer_list init_list) { - d.insert(index, init_list); - return *this; - } - - //! \~english Removes `count` elements from the middle of the array, starting at `index` position. - //! \~russian Удаляет элементы из массива, начиная с позиции `index` в количестве `count`. - //! \~\details - //! \~\sa \a resize(), \a insert(), \a removeOne(), \a removeAll(), \a removeWhere() - inline PIByteArray & remove(size_t index, size_t count = 1) { - d.remove(index, count); - return *this; - } - - //! \~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); - } - - //! \~english Reverses this array. - //! \~russian Обращает порядок следования элементов этого массива. - //! \~\details - //! \~english This method reverses an array [in place](https://en.wikipedia.org/wiki/In-place_algorithm). - //! The first array element becomes the last, and the last array element becomes the first. - //! The reverse method transposes the elements of the calling array object in place, - //! mutating the array, and returning a reference to the array. - //! \~russian Метод reverse() на месте переставляет элементы массива, - //! на котором он был вызван, изменяет массив и возвращает ссылку на него. - //! Первый элемент массива становится последним, а последний — первым. - //! \~\sa \a reversed() - inline PIByteArray & reverse() { - d.reverse(); - return *this; - } - - //! \~english Returns reversed array. - //! \~russian Возвращает перевернутый массив. - //! \~\details - //! \~english Returns a copy of the array with elements in reverse order. - //! The first array element becomes the last, and the last array element becomes the first. - //! \~russian Возвращает копию массива с элементами в обратном порядке. - //! Первый элемент массива становится последним, а последний — первым. - //! \~\sa \a reverse() - inline PIByteArray reversed() const { - PIByteArray ret(*this); - return ret.reverse(); - } - - //! \~english Increases or decreases the size of the array by `add_size` elements. - //! \~russian Увеличивает или уменьшает размер массива на `add_size` элементов. - //! \~\details - //! \~english If `add_size > 0` then elements are added to the end of the array. - //! If `add_size < 0` then elements are removed from the end of the array. - //! If `add_size < 0` and there are fewer elements in the array than specified, then the array becomes empty. - //! \~russian Если `add_size > 0`, то в конец массива добавляются элементы. - //! Если `add_size < 0`, то с конца массива удаляются элементы. - //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. - //! \~\sa \a resize() - inline PIByteArray & enlarge(ssize_t add_size, uchar e = 0) { - d.enlarge(add_size, e); - return *this; - } - - //! \~english Remove no more than one element equal `e`. - //! \~russian Удаляет первый элемент, который равен элементу `e`. - //! \~\details - //! \~\sa \a remove(), \a removeAll(), \a removeWhere() - inline PIByteArray & removeOne(uchar e) { - d.removeOne(e); - return *this; - } - - //! \~english Remove all elements equal `e`. - //! \~russian Удаляет все элементы, равные элементу `e`. - //! \~\details - //! \~\sa \a remove(), \a removeOne(), \a removeWhere() - inline PIByteArray & removeAll(uchar e) { - d.removeAll(e); - return *this; - } - - //! \~english Remove all elements in the array - //! passes the test implemented by the provided function `test`. - //! \~russian Удаляет все элементы, удовлетворяющие условию, - //! заданному в передаваемой функции `test`. - //! \~\details - //! \~\sa \a remove(), \a removeOne(), \a removeWhere() - inline PIByteArray & removeWhere(std::function test) { - d.removeWhere(test); - return *this; - } - - //! \~english Appends the given element `e` to the end of the array. - //! \~russian Добавляет элемент `e` в конец массива. - //! \~\details - //! \~english If size() is less than capacity(), which is most often - //! then the addition will be very fast. - //! In any case, the addition is fast and does not depend on the size of the array. - //! If the new size() is greater than capacity() - //! then all iterators and references - //! (including the past-the-end iterator) are invalidated. - //! Otherwise only the past-the-end iterator is invalidated. - //! \~russian Если size() меньше capacity(), что часто бывает, - //! то добавление будет очень быстрым. - //! В любом случае добавление быстрое и не зависит от размера массива. - //! Если новый size() больше, чем capacity(), - //! то все итераторы и указатели становятся нерабочими. - //! В противном случае все, кроме итераторов, указывающих на конец массива, - //! остаются в рабочем состоянии. - //! \~\sa \a push_front(), \a append(), \a prepend(), \a insert() - inline PIByteArray & push_back(uchar e) { - d.push_back(e); - return *this; - } - - //! \~english Appends the given elements to the end of the array. - //! \~russian Добавляет элементы в конец массива. - //! \~\details - //! \~english Overloaded function. - //! Appends the given elements from - //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). - //! \~russian Перегруженая функция. - //! Добавляет элементы из - //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). - //! \~\sa \a push_back() - inline PIByteArray & push_back(std::initializer_list init_list) { - d.push_back(init_list); - return *this; - } - - //! \~english Appends the given array `v` to the end of the array. - //! \~russian Добавляет массив `v` в конец массива. - //! \~\details - //! \~english Overloaded function. - //! \~russian Перегруженая функция. - //! \~\sa \a push_back() - inline PIByteArray & push_back(const PIByteArray & v) { - d.push_back(v.d); - return *this; - } - - - //! \~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;} - - //! \~english Appends the given element `e` to the begin of the array. - //! \~russian Добавляет элемент `e` в начало массива. - //! \~\details - //! \~english If there is free space at the beginning of the array, - //! which is most often, then the addition will be very fast. - //! In any case, the addition is fast and does not depend on the size of the array. - //! If there is no free space at the beginning of the array - //! then all iterators and references - //! (including the past-the-begin iterator) are invalidated. - //! Otherwise only the past-the-begin iterator is invalidated. - //! \~russian Если в начале массива имеется свободное место, - //! что часто бывает, то добавление будет очень быстрым. - //! В любом случае добавление быстрое и не зависит от размера массива. - //! Если в начале массива нет свободного места, - //! то все итераторы и указатели становятся нерабочими. - //! В противном случае все, кроме итераторов указывающих, на начало массива, - //! остаются в рабочем состоянии. - //! \~\sa \a push_back(), \a append(), \a prepend(), \a insert() - inline PIByteArray & push_front(uchar e) { - d.push_front(e); - return *this; - } - - //! \~english Appends the given array `v` to the begin of the array. - //! \~russian Добавляет массив `v` в начало массива. - //! \~\details - //! \~english Overloaded function. - //! \~russian Перегруженая функция. - //! \~\sa \a push_front() - inline PIByteArray & push_front(const PIByteArray & v) { - d.push_front(v.d); - return *this; - } - - //! \~english Appends the given elements to the begin of the array. - //! \~russian Добавляет элементы в начало массива. - //! \~\details - //! \~english Overloaded function. - //! Appends the given elements from - //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). - //! \~russian Перегруженая функция. - //! Добавляет элементы из - //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). - //! \~\sa \a append() - inline PIByteArray & push_front(std::initializer_list init_list) { - d.push_front(init_list); - return *this; - } - - //! \~english Appends the given element `e` to the begin of the array. - //! \~russian Добавляет элемент `e` в начало массива. - //! \~\details - //! \~english If there is free space at the beginning of the array, - //! which is most often, then the addition will be very fast. - //! In any case, the addition is fast and does not depend on the size of the array. - //! If there is no free space at the beginning of the array - //! then all iterators and references - //! (including the past-the-begin iterator) are invalidated. - //! Otherwise only the past-the-begin iterator is invalidated. - //! \~russian Если в начале массива имеется свободное место, - //! что часто бывает, то добавление будет очень быстрым. - //! В любом случае добавление быстрое и не зависит от размера массива. - //! Если в начале массива нет свободного места, - //! то все итераторы и указатели становятся нерабочими. - //! В противном случае все, кроме итераторов указывающих, на начало массива, - //! остаются в рабочем состоянии. - //! \~\sa \a push_back(), \a append(), \a prepend(), \a insert() - inline PIByteArray & prepend(uchar e) { - d.prepend(e); - return *this; - } - - //! \~english Appends the given array `v` to the begin of the array. - //! \~russian Добавляет массив `v` в начало массива. - //! \~\details - //! \~english Overloaded function. - //! \~russian Перегруженая функция. - //! \~\sa \a prepend() - inline PIByteArray & prepend(const PIByteArray & v) { - d.prepend(v.d); - return *this; - } - - //! \~english Appends the given elements to the begin of the array. - //! \~russian Добавляет элементы в начало массива. - //! \~\details - //! \~english Overloaded function. - //! Appends the given elements from - //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). - //! \~russian Перегруженая функция. - //! Добавляет элементы из - //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). - //! \~\sa \a append() - inline PIByteArray & prepend(std::initializer_list init_list) { - d.prepend(init_list); - return *this; - } - - //! \~english Remove one element from the end of the array. - //! \~russian Удаляет один элемент с конца массива. - //! \~\details - //! \~english Deleting an element from the end is very fast - //! and does not depend on the size of the array. - //! \~russian Удаление элемента с конца выполняется очень быстро - //! и не зависит от размера массива. - //! \~\sa \a pop_front(), \a take_back(), \a take_front() - inline PIByteArray & pop_back() { - d.pop_back(); - return *this; - } - - //! \~english Remove one element from the begining of the array. - //! \~russian Удаляет один элемент с начала массива. - //! \~\details - //! \~english Removing an element from the beginning takes longer than from the end. - //! This time is directly proportional to the size of the array. - //! All iterators and references are invalidated. - //! \~russian Удаление элемента с начала выполняется дольше, чем с конца. - //! Это время прямопропорционально размеру массива. - //! При удалении элемента все итераторы и указатели становятся нерабочими. - //! \~\sa \a pop_back(), \a take_back(), \a take_front() - inline PIByteArray & pop_front() { - d.pop_front(); - return *this; - } - - //! \~english Remove one element from the end of the array and return it. - //! \~russian Удаляет один элемент с начала массива и возвращает его. - //! \~\details - //! \~\sa \a take_front(), \a pop_back(), \a pop_front() - 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(); - } - - //! \~english Returns a new array with all elements - //! that pass the test implemented by the provided function `test`. - //! \~russian Возвращает новый массив со всеми элементами, - //! прошедшими проверку, задаваемую в передаваемой функции `test`. - //! \~\details - //! \~\code - //! PIByteArray v{3, 2, 5, 2, 7}; - //! PIByteArray v2 = v.filter([](const uchar & i){return i > 2;}); - //! piCout << v2; // {3, 5, 7} - //! \endcode - //! \~\sa \a map(), \a any(), \a every() - inline PIByteArray filter(std::function 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)` для каждого элемента массива. - //! \~\details - //! \~russian Не позволяет изменять элементы массива. - //! Для редактирования элементов используйте функцию вида `void f(uchar & e)`. - //! \~english Does not allow changing array elements. - //! To edit elements, use the function like `void f(T & e)` - //! \~\code - //! PIByteArray v{1, 2, 3, 4, 5}; - //! int s = 0; - //! v.forEach([&s](const uchar & e){s += e;}); - //! piCout << s; // 15 - //! \endcode - //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() - inline void forEach(std::function f) const { - d.forEach(f); - } - - //! \~english Execute function `void f(uchar & e)` for every element in array. - //! \~russian Выполняет функцию `void f(uchar & e)` для каждого элемента массива. - //! \~\details - //! \~english Overloaded function. - //! Allows you to change the elements of the array. - //! \~russian Перегруженая функция. - //! Позволяет изменять элементы массива. - //! \~\code - //! PIByteArray v{1, 2, 3, 4, 5}; - //! v.forEach([](uchar & e){e++;}); - //! piCout << v; // {2, 3, 4, 5, 6} - //! \endcode - //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() - inline PIByteArray & forEach(std::function f) { - d.forEach(f); - return *this; - } - - //! \~english Сreates a new array populated with the results - //! of calling a provided function `ST f(const uchar & e)` on every element in the calling array. - //! \~russian Создаёт новый массив с результатом вызова указанной функции - //! `ST f(const T & e)` для каждого элемента массива. - //! \~\details - //! \~english Calls a provided function`ST f(const uchar & e)` - //! once for each element in an array, in order, - //! and constructs a new array from the results. - //! \~russian Метод `map` вызывает переданную функцию `ST f(const uchar & e)` - //! один раз для каждого элемента в порядке их появления - //! и конструирует новый массив из результатов её вызова. - //! \~\code - //! PIByteArray v{0x31, 0x0A, 0xFF}; - //! PIStringList sl = v.map([](const uchar & i){return PIString::fromNumber(i, 16);}); - //! piCout << sl; {"31", "A", "FF"} - //! \endcode - //! \~\sa \a forEach(), \a reduce() - template - inline PIDeque map(std::function f) const { - return d.map(f); - } - - //! \~english Applies the function `ST f(const uchar & e, const ST & acc)` - //! to each element of the array (from left to right), returns one value. - //! \~russian Применяет функцию `ST f(const uchar & e, const ST & acc)` - //! к каждому элементу массива (слева-направо), возвращает одно значение. - //! \~\details - //! \~english The reduce() method performs the `f` function - //! once for each element in the array. - //! If the `initial` argument is passed when calling reduce(), - //! then when the function `f` is called for the first time, - //! the value of `acc` will be assigned to `initial`. - //! If the array is empty, the value `initial` will be returned. - //! \param f is a function like `ST f(const uchar & e, const ST & acc)`, - //! executed for each element of the array. It takes two arguments: - //! * **e** - current element of the array - //! * **acc** - accumulator accumulating the value - //! which this function returns after visiting the next element - //! - //! \param initial _optional_ Object used as the second argument - //! when the `f` function is first called. - //! \~russian Метод reduce() выполняет функцию `f` - //! один раз для каждого элемента, присутствующего в массиве. - //! Если при вызове reduce() передан аргумент `initial`, - //! то при первом вызове функции `f` значение `acc` - //! будет равным значению `initial`. - //! Если массив пустой то будет возвращено значение `initial`. - //! \param f Функция, вида `ST f(const uchar & e, const ST & acc)`, - //! выполняющаяся для каждого элемента массива. - //! Она принимает два аргумента: - //! * **e** - текущий элемент массива - //! * **acc** - аккумулятор, аккумулирующий значение - //! которое возвращает эта функция после посещения очередного элемента - //! - //! \param initial _опциональный_ Объект, - //! используемый в качестве второго аргумента при первом вызове функции `f`. - //! - //! \~\code - //! PIByteArray v{1, 2, 3, 4, 5}; - //! PIString s = v.reduce([](const uchar & e, const PIString & acc){return acc + PIString::fromNumber(e);}); - //! piCout << s; // "12345" - //! \endcode - //! \~\sa \a forEach(), \a map() - template - inline ST reduce(std::function f, const ST & initial = ST()) const { - return d.reduce(f, initial); - } - - //! \~english Convert data to Base 64 and return this byte array - //! \~russian Преобразует данные в Base 64 и возвращает текущий массив - PIByteArray & convertToBase64(); - - //! \~english Convert data from Base 64 and return this byte array - //! \~russian Преобразует данные из Base 64 и возвращает текущий массив - PIByteArray & convertFromBase64(); - - //! \~english Return converted to Base 64 data - //! \~russian Возвращает копию байтового массива, преобразованного в Base 64 - PIByteArray toBase64() const; - - 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;} - - //! \~english Return string representation of data, each byte in "base" base, separated by spaces - //! \~russian Возвращает текстовое представление байтового массива, каждый байт в "base" системе, с пробелами - PIString toString(int base = 16) const; - - //! \~english - //! Returns a hex encoded copy of the byte array, without spaces. - //! The hex encoding uses the numbers 0-9 and the letters a-f. - //! \~russian - //! Возвращает шестнадцатеричное представление массива, без пробелов. - //! Оно использует цифры 0-9 и буквы a-f. - PIString toHex() const; - - //! \~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;} - - //! \~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;} - - //! \~english Add to the end "t" - //! \~russian Добавляет в конец массива байт "t" - PIByteArray & append(uchar t) {push_back(t); return *this;} - - //! \~english Appends the given elements to the end of the array. - //! \~russian Добавляет элементы в конец массива. - //! \~\details - //! \~english Overloaded function. - //! Appends the given elements from - //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). - //! \~russian Перегруженая функция. - //! Добавляет элементы из - //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). - //! \~\sa \a push_back() - inline PIByteArray & append(std::initializer_list init_list) { - d.append(init_list); - return *this; - } - - //! \~english Returns 8-bit checksum - //! \~russian Возвращает 8-битную контрольную сумму - uchar checksumPlain8(bool inverse = true) const; - - //! \~english Returns 32-bit checksum - //! \~russian Возвращает 32-битную контрольную сумму - uint checksumPlain32(bool inverse = true) const; - - //! \~english Returns 8-bit checksum CRC-8 - //! \~russian Возвращает 8-битную контрольную сумму CRC-8 - uchar checksumCRC8() const; - - //! \~english Returns 16-bit checksum CRC-16 - //! \~russian Возвращает 16-битную контрольную сумму CRC-16 - ushort checksumCRC16() const; - - //! \~english Returns 32-bit checksum CRC-32 - //! \~russian Возвращает 32-битную контрольную сумму CRC-32 - uint checksumCRC32() const; - - //! \~english Returns hash of content - //! \~russian Возвращает хэш содержимого - uint hash() const; - - void operator =(const PIDeque & 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 =(PIByteArray && o) {swap(o); return *this;} - - static PIByteArray fromUserInput(PIString str); - - static PIByteArray fromHex(PIString str); - - //! \~english Return converted from Base 64 data - //! \~russian Возвращает массив из Base 64 представления - static PIByteArray fromBase64(const PIByteArray & base64); - static PIByteArray fromBase64(const PIString & base64); - - - bool binaryStreamAppendImp(const void * d_, size_t s) { - append(d_, s); - return true; - } - bool binaryStreamTakeImp(void * d_, size_t s) { - size_t rs = size(); - if (rs > s) rs = s; - memcpy(d_, data(), rs); - remove(0, rs); - return rs == s; - } - - ssize_t binaryStreamSizeImp() const {return size();} - -private: - PIDeque d; - -}; - -//! \relatesalso PIByteArray -//! \~english Byte arrays compare operator -//! \~russian Оператор сравнения -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; - } - return v0.size() < v1.size(); -} - -//! \relatesalso PIByteArray -//! \~english Byte arrays compare operator -//! \~russian Оператор сравнения -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; - } - return v0.size() > v1.size(); -} - -//! \relatesalso PIByteArray -//! \~english Byte arrays compare operator -//! \~russian Оператор сравнения -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; - } - return false; -} - -//! \relatesalso PIByteArray -//! \~english Byte arrays compare operator -//! \~russian Оператор сравнения -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; - } - return true; -} - -#ifdef PIP_STD_IOSTREAM -//! \relatesalso PIByteArray \brief Output to std::ostream operator -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); - - -//! \relatesalso PIBinaryStream -//! \~english Store operator. -//! \~russian Оператор сохранения. -BINARY_STREAM_WRITE(PIByteArray) { - s.binaryStreamAppend((int)v.size_s()); - s.binaryStreamAppend(v.data(), v.size()); - return s; -} - -//! \relatesalso PIBinaryStream -//! \~english Restore operator. -//! \~russian Оператор извлечения. -BINARY_STREAM_READ(PIByteArray) { - v.resize(s.binaryStreamTakeInt()); - s.binaryStreamTake(v.data(), v.size()); - return s; -} - - -//! \relatesalso PIByteArray -//! \~english Returns PIByteArray::hash() of "ba" -//! \~russian Возвращает PIByteArray::hash() от "ba" -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);} - - -//! \relatesalso PIByteArray -//! \~english Store "value" to bytearray and returns it -//! \~russian Сохраняет "value" в байтовый массив и возвращает его -template PIByteArray piSerialize(const T & value) { - PIByteArray ret; - ret << value; - return ret; -} - -//! \relatesalso PIByteArray -//! \~english Restore type "T" from bytearray "data" and returns it -//! \~russian Извлекает тип "T" из байтового массива "data" и возвращает его -template T piDeserialize(const PIByteArray & data) { - T ret; - if (!data.isEmpty()) { - PIByteArray ba(data); - ba >> ret; - } - return ret; -} - - -#endif // PIBYTEARRAY_H +/*! \file pibytearray.h + * \ingroup Types + * \~\brief + * \~english Byte array + * \~russian Байтовый массив +*/ +/* + 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 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 . +*/ + +#ifndef PIBYTEARRAY_H +#define PIBYTEARRAY_H + +#include "pichar.h" +#include "pibinarystream.h" +#include + +class PIString; +class PIByteArray; + + +//! \ingroup Types +//! \~\brief +//! \~english The %PIByteArray class provides an array of bytes. +//! \~russian Класс %PIByteArray представляет собой массив байтов. +class PIP_EXPORT PIByteArray: public PIBinaryStream +{ +public: + typedef ::PIMemoryBlock RawData DEPRECATEDM("use PIMemoryBlock instead"); + + //! \~english Constructs an empty byte array + //! \~russian Создает пустой байтовый массив + PIByteArray() {} + + //! \~english Constructs copy of byte array "o" + //! \~russian Создает копию байтового массива "o" + PIByteArray(const PIByteArray & o): d(o.d) {} + + //! \~english Constructs copy of byte array "o" + //! \~russian Создает копию байтового массива "o" + PIByteArray(const PIDeque & o): d(o) {} + + PIByteArray(PIByteArray && o): d(std::move(o.d)) {} + + //! \~english Constructs 0-filled byte array with size "size" + //! \~russian Создает заполненный "0" байтовый массив размером "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)) {} + + //! \~english Constructs byte array with size "size" filled by "t" + //! \~russian Создает заполненный "t" байтовый массив размером "size" + PIByteArray(const uint size, uchar t): d(size, t) {} + + //! \~english Contructs array from + //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian Создает массив из + //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). + //! \~\details + //! \~\code + //! PIByteArray v{1,2,3}; + //! piCout << v; // {1, 2, 3} + //! \endcode + PIByteArray(std::initializer_list 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); + } + + //! \~english Iterator to the first element. + //! \~russian Итератор на первый элемент. + //! \~\details ![begin, end](doc/images/pivector_begin.png) + //! + //! \~english If the array is empty, the returned iterator is equal to \a end(). + //! \~russian Если массив - пуст, возвращаемый итератор будет равен \a end(). + //! \~\return \ref stl_iterators + //! \~\sa \a end(), \a rbegin(), \a rend() + inline PIDeque::iterator begin() {return d.begin();} + + //! \~english Iterator to the element following the last element. + //! \~russian Итератор на элемент, следующий за последним элементом. + //! \~\details ![begin, end](doc/images/pivector_begin.png) + //! + //! \~english This element acts as a placeholder; + //! attempting to access it results in undefined behavior. + //! \~russian Этот элемент существует лишь условно, + //! попытка доступа к нему приведёт к выходу за разрешенную память. + //! \~\return \ref stl_iterators + //! \~\sa \a begin(), \a rbegin(), \a rend() + inline PIDeque::iterator end() {return d.end();} + + inline PIDeque::const_iterator begin() const {return d.begin();} + inline PIDeque::const_iterator end() const {return d.end();} + + //! \~english Returns a reverse iterator to the first element of the reversed array. + //! \~russian Обратный итератор на первый элемент. + //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) + //! + //! \~english It corresponds to the last element of the non-reversed array. + //! If the array is empty, the returned iterator is equal to \a rend(). + //! \~russian Итератор для прохода массива в обратном порядке. + //! Указывает на последний элемент. + //! Если массив пустой, то совпадает с итератором \a rend(). + //! \~\return \ref stl_iterators + //! \~\sa \a rend(), \a begin(), \a end() + inline PIDeque::reverse_iterator rbegin() {return d.rbegin();} + + //! \~english Returns a reverse iterator to the element. + //! following the last element of the reversed array. + //! \~russian Обратный итератор на элемент, следующий за последним элементом. + //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) + //! + //! \~english It corresponds to the element preceding the first element of the non-reversed array. + //! This element acts as a placeholder, attempting to access it results in undefined behavior. + //! \~russian Итератор для прохода массива в обратном порядке. + //! Указывает на элемент, предшествующий первому элементу. + //! Этот элемент существует лишь условно, + //! попытка доступа к нему приведёт к выходу за разрешенную память. + //! \~\return \ref stl_iterators + //! \~\sa \a rbegin(), \a begin(), \a end() + inline PIDeque::reverse_iterator rend() {return d.rend();} + + inline PIDeque::const_reverse_iterator rbegin() const {return d.rbegin();} + inline PIDeque::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();} + + //! \~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();} + + //! \~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();} + + //! \~english Number of elements that the container has currently allocated space for. + //! \~russian Количество элементов, для которого сейчас выделена память массивом. + //! \~\details + //! \~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();} + + //! \~english Checks if the container has no elements. + //! \~russian Проверяет пуст ли массив. + //! \~\return + //! \~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();} + + //! \~english Checks if the container has elements. + //! \~russian Проверяет не пуст ли массив. + //! \~\return + //! \~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();} + + //! \~english Tests whether at least one element in the array + //! passes the test implemented by the provided function `test`. + //! \~russian Проверяет, удовлетворяет ли какой-либо элемент массива условию, + //! заданному в передаваемой функции `test`. + //! \~\return + //! \~english **true** if, in the array, + //! it finds an element for which the provided function returns **true**; + //! otherwise it returns **false**. Always returns **false** if is empty. + //! \~russian **true** если хотя бы для одного элемента + //! передаваемая функция возвращает **true**, в остальных случаях **false**. + //! Метод возвращает **false** при любом условии для пустого массива. + //! \~\details + //! \~\sa \a every(), \a contains(), \a entries(), \a forEach() + inline bool any(std::function test) const { + return d.any(test); + } + + //! \~english Tests whether all elements in the array passes the test + //! implemented by the provided function `test`. + //! \~russian Проверяет, удовлетворяют ли все элементы массива условию, + //! заданному в передаваемой функции `test`. + //! \~\return + //! \~english **true** if, in the array, + //! it finds an element for which the provided function returns **true**; + //! otherwise it returns **false**. Always returns **true** if is empty. + //! \~russian **true** если для всех элементов передаваемая функция возвращает **true**, + //! в остальных случаях **false**. + //! Метод возвращает **true** при любом условии для пустого массива. + //! \~\details + //! \~\sa \a any(), \a contains(), \a entries(), \a forEach() + inline bool every(std::function test) const { + return d.every(test); + } + + //! \~english Full access to element by `index`. + //! \~russian Полный доступ к элементу по индексу `index`. + //! \~\details + //! \~english Element index starts from `0`. + //! Element index must be in range from `0` to `size()-1`. + //! Otherwise will be undefined behavior. + //! \~russian Индекс элемента считается от `0`. + //! Индекс элемента должен лежать в пределах от `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];} + + //! \~english Read only access to element by `index`. + //! \~russian Доступ исключительно на чтение к элементу по индексу `index`. + //! \~\details + //! \~english Element index starts from `0`. + //! Element index must be in range from `0` to `size()-1`. + //! Otherwise will be undefined behavior. + //! \~russian Индекс элемента считается от `0`. + //! Индекс элемента должен лежать в пределах от `0` до `size()-1`. + //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. + inline uchar at(size_t index) const {return d.at(index);} + + //! \~english Last element. + //! \~russian Последний элемент массива. + //! \~\details + //! \~english Returns a reference to the last item in the array. + //! This function assumes that the array isn't empty. + //! Otherwise will be undefined behavior. + //! \~russian Возвращает ссылку на последний элемент в массиве. + //! Эта функция предполагает, что массив не пустой. + //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. + inline uchar & back() {return d.back();} + inline uchar back() const {return d.back();} + + //! \~english Last element. + //! \~russian Первый элемент массива. + //! \~\details + //! \~english Returns a reference to the last item in the array. + //! This function assumes that the array isn't empty. + //! Otherwise will be undefined behavior. + //! \~russian Возвращает ссылку на пенрвый элемент в массиве. + //! Эта функция предполагает, что массив не пустой. + //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. + inline uchar & front() {return d.front();} + inline uchar front() const {return d.front();} + + //! \~english Tests if element `e` exists in the array. + //! \~russian Проверяет наличие элемента `e` в массиве. + //! \~\details + //! \~english Optional argument `start` - the position in this array at which to begin searching. + //! If the index is greater than or equal to the array's size, + //! **false** is returned, which means the array will not be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Note: if the provided index is negative, + //! the array is still searched from front to back. + //! Default: 0 (entire array is searched). + //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. + //! Если индекс больше или равен длине массива, + //! возвращается **false**, что означает, что массив даже не просматривается. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. + //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. + //! \~\code + //! PIByteArray v{1, 2, 3, 4}; + //! piCout << v.contains(3); // true + //! piCout << v.contains(5); // false + //! piCout << v.contains(3, 3); // false + //! piCout << v.contains(3, -2); // true + //! piCout << v.contains(3, -99); // true + //! \endcode + //! \~\return + //! \~english **true** if the array contains an occurrence of element `e`, + //! otherwise it returns **false**. + //! \~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); + } + + //! \~english Count elements equal `e` in the array. + //! \~russian Подсчитывает количество элементов, совпадающих с элементом `e` в массиве. + //! \~\details + //! \~english Optional argument `start` - the position in this array at which to begin searching. + //! If the index is greater than or equal to the array's size, + //! 0 is returned, which means the array will not be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Note: if the provided index is negative, + //! the array is still searched from front to back. + //! Default: 0 (entire array is searched). + //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. + //! Если индекс больше или равен длине массива, + //! возвращается 0, что означает, что массив даже не просматривается. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. + //! Значение по умолчанию равно 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); + } + + //! \~english Count elements in the array passes the test implemented by the provided function `test`. + //! \~russian Подсчитывает количество элементов в массиве, + //! проходящих по условию, заданному в передаваемой функции `test`. + //! \~\details + //! \~english Overloaded function. + //! Optional argument `start` - the position in this array at which to begin searching. + //! If the index is greater than or equal to the array's size, + //! 0 is returned, which means the array will not be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Note: if the provided index is negative, + //! the array is still searched from front to back. + //! Default: 0 (entire array is searched). + //! \~russian Перегруженная функция. + //! Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. + //! Если индекс больше или равен длине массива, + //! возвращается 0, что означает, что массив даже не просматривается. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. + //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. + //! \~\sa \a every(), \a any(), \a contains(), \a indexWhere() + inline int entries(std::function 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. + //! \~russian Возвращает первый индекс, по которому данный элемент `e` + //! может быть найден в массиве или `-1`, если такого индекса нет. + //! \~\details + //! \~english Optional argument `start` - the position in this array at which to begin searching. + //! If the index is greater than or equal to the array's size, + //! `-1` is returned, which means the array will not be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Note: if the provided index is negative, + //! the array is still searched from front to back. + //! Default: 0 (entire array is searched). + //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. + //! Если индекс больше или равен длине массива, + //! возвращается `-1`, что означает, что массив даже не просматривается. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. + //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. + //! \~\code + //! PIByteArray v{2, 5, 9}; + //! piCout << v.indexOf(2); // 0 + //! piCout << v.indexOf(7); // -1 + //! piCout << v.indexOf(9, 2); // 2 + //! piCout << v.indexOf(2, -1); // -1 + //! 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); + } + + //! \~english Returns the first index passes the test implemented by the provided function `test`, + //! or `-1` if it is not present. + //! can be found in the array, or `-1` if it is not present. + //! \~russian Возвращает первый индекс элемента проходящего по условию, + //! заданному в передаваемой функции `test`, или `-1`, если таких элементов нет. + //! \~\details + //! \~english Optional argument `start` - the position in this array at which to begin searching. + //! If the index is greater than or equal to the array's size, + //! `-1` is returned, which means the array will not be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Note: if the provided index is negative, + //! the array is still searched from front to back. + //! Default: 0 (entire array is searched). + //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. + //! Если индекс больше или равен длине массива, + //! возвращается `-1`, что означает, что массив даже не просматривается. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. + //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. + //! \~\code + //! PIByteArray v{2, 5, 9}; + //! piCout << v.indexWhere([](const uchar & s){return s > 3;}); // 1 + //! piCout << v.indexWhere([](const uchar & s){return s > 3;}, 2); // 2 + //! 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 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. + //! \~russian Возвращает последний индекс, по которому данный элемент `e` + //! может быть найден в массиве или `-1`, если такого индекса нет. + //! \~\details + //! \~english Optional argument `start` - the position in this array + //! at which to start searching backwards. + //! If the index is greater than or equal to the array's size, + //! causes the whole array to be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Therefore, if calculated index less than 0, + //! the array is not searched, and the method returns `-1`. + //! Note: if the provided index is negative, + //! the array is still searched from back to front. + //! Default: -1 (entire array is searched). + //! \~russian Опциональный аргумент `start` указывает на индекс + //! c которого начинать поиск в обратном направлении. + //! Если индекс больше или равен длине массива, просматривается весь массив. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от конца к началу. + //! Если рассчитанный индекс оказывается меньше 0, массив даже не просматривается. + //! Значение по умолчанию равно `-1`, что равно индексу последнего элемента + //! и означает, что просматривается весь массив. + //! \~\code + //! PIByteArray v{2, 5, 9, 2}; + //! piCout << v.lastIndexOf(2); // 3 + //! piCout << v.lastIndexOf(7); // -1 + //! piCout << v.lastIndexOf(2, 2); // 0 + //! piCout << v.lastIndexOf(2, -3); // 0 + //! piCout << v.lastIndexOf(2, -300); // -1 + //! 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); + } + + //! \~english Returns the last index passes the test implemented by the provided function `test`, + //! or `-1` if it is not present. + //! \~russian Возвращает последний индекс элемента проходящего по условию, + //! заданному в передаваемой функции `test`, или `-1`, если таких элементов нет. + //! \~\details + //! \~english Optional argument `start` - the position in this array + //! at which to start searching backwards. + //! If the index is greater than or equal to the array's size, + //! causes the whole array to be searched. + //! If the provided index value is a negative number, + //! it is taken as the offset from the end of the array. + //! Therefore, if calculated index less than 0, + //! the array is not searched, and the method returns `-1`. + //! Note: if the provided index is negative, + //! the array is still searched from back to front. + //! Default: -1 (entire array is searched). + //! \~russian Опциональный аргумент `start` указывает на индекс + //! c которого начинать поиск в обратном направлении. + //! Если индекс больше или равен длине массива, просматривается весь массив. + //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. + //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от конца к началу. + //! Если рассчитанный индекс оказывается меньше 0, массив даже не просматривается. + //! Значение по умолчанию равно `-1`, что равно индексу последнего элемента + //! и означает, что просматривается весь массив. + //! \~\sa \a indexOf(), \a lastIndexOf(), \a indexWhere(), \a contains() + inline ssize_t lastIndexWhere(std::function test, ssize_t start = -1) const { + return d.lastIndexWhere(test, start); + } + + //! \~english Pointer to array + //! \~russian Указатель на память массива + //! \~\details + //! \~english Optional argument `index` the position in this array, + //! where is pointer. Default: start of array. + //! \~russian Опциональный аргумент `index` указывает на индекс c которого брать указатель. + //! По умолчанию указывает на начало массива. + inline uchar * data(size_t index = 0) {return d.data(index);} + + //! \~english Read only pointer to array + //! \~russian Указатель на память массива только для чтения. + //! \~\details + //! \~english The pointer can be used to access and modify the items in the array. + //! The pointer remains valid as long as the array isn't reallocated. + //! Optional argument `index` the position in this array, + //! where is pointer. Default: start of array. + //! \~russian Указатель можно использовать для доступа и изменения элементов в массиве. + //! Указатель остается действительным только до тех пор, пока массив не будет перераспределен. + //! Опциональный аргумент `index` указывает на индекс c которого брать указатель. + //! По умолчанию указывает на начало массива. + inline const uchar * data(size_t index = 0) const {return d.data(index);} + + //! \~english Clear array, remove all elements. + //! \~russian Очищает массив, удаляет все элементы. + //! \~\details + //! \~\note + //! \~english Reserved memory will not be released. + //! \~russian Зарезервированная память не освободится. + //! \~\sa \a resize() + inline PIByteArray & clear() { + resize(0); + return *this; + } + + //! \~english Assigns element 'e' to all items in the array. + //! \~russian Заполняет весь массив копиями элемента 'e'. + //! \~\details + //! \~\sa \a resize() + inline PIByteArray & fill(uchar e = 0) { + d.fill(e); + return *this; + } + + //! \~english Assigns result of function 'f(size_t i)' to all items in the array. + //! \~russian Заполняет весь массив результатом вызова функции 'f(size_t i)'. + //! \~\details + //! \~\sa \a resize() + inline PIByteArray & fill(std::function f) { + d.fill(f); + return *this; + } + + //! \~english Same as \a fill(). + //! \~russian Тоже самое что и \a fill(). + //! \~\sa \a fill(), \a resize() + inline PIByteArray & assign(uchar e = 0) {return fill(e);} + + //! \~english First does `resize(new_size)` then `fill(e)`. + //! \~russian Сначала делает `resize(new_size)`, затем `fill(e)`. + //! \~\sa \a fill(), \a resize() + inline PIByteArray & assign(size_t new_size, uchar e) { + resize(new_size); + return fill(e); + } + + //! \~english Sets size of the array, new elements are copied from `e`. + //! \~russian Устанавливает размер массива, новые элементы копируются из `e`. + //! \~\details + //! \~english If `new_size` is greater than the current \a size(), + //! elements are added to the end; the new elements are initialized from `e`. + //! If `new_size` is less than the current \a size(), elements are removed from the end. + //! \~russian Если `new_size` больше чем текущий размер массива \a size(), + //! новые элементы добавляются в конец массива и создаются из `e`. + //! Если `new_size` меньше чем текущий размер массива \a size(), + //! лишние элементы удаляются с конца массива. + //! \~\sa \a size(), \a clear() + inline PIByteArray & resize(size_t new_size, uchar e = 0) { + d.resize(new_size, e); + return *this; + } + + //! \~english Sets size of the array, new elements created by function `f(size_t i)`. + //! \~russian Устанавливает размер массива, новые элементы создаются функцией `f(size_t i)`. + //! \~\details + //! \~english If `new_size` is greater than the current \a size(), + //! elements are added to the end; the new elements created by function `f(size_t i)`. + //! If `new_size` is less than the current \a size(), elements are removed from the end. + //! \~russian Если `new_size` больше чем текущий размер массива \a size(), + //! новые элементы добавляются в конец массива и функцией `f(size_t i)`. + //! Если `new_size` меньше чем текущий размер массива \a size(), + //! лишние элементы удаляются с конца массива. + //! \~\sa \a size(), \a clear() + inline PIByteArray & resize(size_t new_size, std::function f) { + d.resize(new_size, f); + return *this; + } + + //! \~english Return resized byte array + //! \~russian Возвращает копию байтового массива с измененным размером + PIByteArray resized(uint new_size) const { + PIByteArray ret(new_size); + memcpy(ret.data(), data(), new_size); + return ret; + } + + //! \~english Attempts to allocate memory for at least `new_size` elements. + //! \~russian Резервируется память под как минимум `new_size` элементов. + //! \~\details + //! \~english If you know in advance how large the array will be, + //! you should call this function to prevent reallocations and memory fragmentation. + //! If `new_size` is greater than the current \a capacity(), + //! new storage is allocated, otherwise the function does nothing. + //! This function does not change the \a size() of the array. + //! \~russian Если вы заранее знаете, насколько велик будет массив, + //! вы можете вызвать эту функцию, чтобы предотвратить перераспределение и фрагментацию памяти. + //! Если размер `new_size` больше чем выделенная память \a capacity(), + //! то произойдёт выделение новой памяти и перераспределение массива. + //! Эта функция не изменяет количество элементов в массиве \a size(). + //! \~\sa \a size(), \a capacity(), \a resize() + inline PIByteArray & reserve(size_t new_size) { + d.reserve(new_size); + return *this; + } + + //! \~english Inserts value `e` at `index` position in the array. + //! \~russian Вставляет значение `e` в позицию `index` в массиве. + //! \~\details + //! \~english The index must be greater than 0 and less than or equal to \a size(). + //! \~russian Индекс должен быть больше 0 и меньше или равен \a size(). + //! \~\sa \a append(), \a prepend(), \a remove() + inline PIByteArray & insert(size_t index, uchar e = 0) { + d.insert(index, e); + return *this; + } + + //! \~english Inserts array `v` at `index` position in the array. + //! \~russian Вставляет массив `v` в позицию `index` в массиве. + //! \~\details + //! \~english The index must be greater than or equal to 0 and less than or equal to \a size(). + //! \~russian Индекс должен быть больше или равен 0 и меньше или равен \a size(). + //! \~\sa \a append(), \a prepend(), \a remove() + inline PIByteArray & insert(size_t index, const PIByteArray & v) { + d.insert(index, v.d); + return *this; + } + + //! \~english Inserts the given elements at `index` position in the array. + //! \~russian Вставляет элементы в позицию `index` в массиве. + //! \~\details + //! \~english The index must be greater than or equal to 0 and less than or equal to \a size(). + //! Inserts the given elements from + //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian Индекс должен быть больше или равен 0 и меньше или равен \a size(). + //! Вставляет элементы из + //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). + //! \~\sa \a append(), \a prepend(), \a remove() + inline PIByteArray & insert(size_t index, std::initializer_list init_list) { + d.insert(index, init_list); + return *this; + } + + //! \~english Removes `count` elements from the middle of the array, starting at `index` position. + //! \~russian Удаляет элементы из массива, начиная с позиции `index` в количестве `count`. + //! \~\details + //! \~\sa \a resize(), \a insert(), \a removeOne(), \a removeAll(), \a removeWhere() + inline PIByteArray & remove(size_t index, size_t count = 1) { + d.remove(index, count); + return *this; + } + + //! \~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); + } + + //! \~english Reverses this array. + //! \~russian Обращает порядок следования элементов этого массива. + //! \~\details + //! \~english This method reverses an array [in place](https://en.wikipedia.org/wiki/In-place_algorithm). + //! The first array element becomes the last, and the last array element becomes the first. + //! The reverse method transposes the elements of the calling array object in place, + //! mutating the array, and returning a reference to the array. + //! \~russian Метод reverse() на месте переставляет элементы массива, + //! на котором он был вызван, изменяет массив и возвращает ссылку на него. + //! Первый элемент массива становится последним, а последний — первым. + //! \~\sa \a reversed() + inline PIByteArray & reverse() { + d.reverse(); + return *this; + } + + //! \~english Returns reversed array. + //! \~russian Возвращает перевернутый массив. + //! \~\details + //! \~english Returns a copy of the array with elements in reverse order. + //! The first array element becomes the last, and the last array element becomes the first. + //! \~russian Возвращает копию массива с элементами в обратном порядке. + //! Первый элемент массива становится последним, а последний — первым. + //! \~\sa \a reverse() + inline PIByteArray reversed() const { + PIByteArray ret(*this); + return ret.reverse(); + } + + //! \~english Increases or decreases the size of the array by `add_size` elements. + //! \~russian Увеличивает или уменьшает размер массива на `add_size` элементов. + //! \~\details + //! \~english If `add_size > 0` then elements are added to the end of the array. + //! If `add_size < 0` then elements are removed from the end of the array. + //! If `add_size < 0` and there are fewer elements in the array than specified, then the array becomes empty. + //! \~russian Если `add_size > 0`, то в конец массива добавляются элементы. + //! Если `add_size < 0`, то с конца массива удаляются элементы. + //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. + //! \~\sa \a resize() + inline PIByteArray & enlarge(ssize_t add_size, uchar e = 0) { + d.enlarge(add_size, e); + return *this; + } + + //! \~english Remove no more than one element equal `e`. + //! \~russian Удаляет первый элемент, который равен элементу `e`. + //! \~\details + //! \~\sa \a remove(), \a removeAll(), \a removeWhere() + inline PIByteArray & removeOne(uchar e) { + d.removeOne(e); + return *this; + } + + //! \~english Remove all elements equal `e`. + //! \~russian Удаляет все элементы, равные элементу `e`. + //! \~\details + //! \~\sa \a remove(), \a removeOne(), \a removeWhere() + inline PIByteArray & removeAll(uchar e) { + d.removeAll(e); + return *this; + } + + //! \~english Remove all elements in the array + //! passes the test implemented by the provided function `test`. + //! \~russian Удаляет все элементы, удовлетворяющие условию, + //! заданному в передаваемой функции `test`. + //! \~\details + //! \~\sa \a remove(), \a removeOne(), \a removeWhere() + inline PIByteArray & removeWhere(std::function test) { + d.removeWhere(test); + return *this; + } + + //! \~english Appends the given element `e` to the end of the array. + //! \~russian Добавляет элемент `e` в конец массива. + //! \~\details + //! \~english If size() is less than capacity(), which is most often + //! then the addition will be very fast. + //! In any case, the addition is fast and does not depend on the size of the array. + //! If the new size() is greater than capacity() + //! then all iterators and references + //! (including the past-the-end iterator) are invalidated. + //! Otherwise only the past-the-end iterator is invalidated. + //! \~russian Если size() меньше capacity(), что часто бывает, + //! то добавление будет очень быстрым. + //! В любом случае добавление быстрое и не зависит от размера массива. + //! Если новый size() больше, чем capacity(), + //! то все итераторы и указатели становятся нерабочими. + //! В противном случае все, кроме итераторов, указывающих на конец массива, + //! остаются в рабочем состоянии. + //! \~\sa \a push_front(), \a append(), \a prepend(), \a insert() + inline PIByteArray & push_back(uchar e) { + d.push_back(e); + return *this; + } + + //! \~english Appends the given elements to the end of the array. + //! \~russian Добавляет элементы в конец массива. + //! \~\details + //! \~english Overloaded function. + //! Appends the given elements from + //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian Перегруженая функция. + //! Добавляет элементы из + //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). + //! \~\sa \a push_back() + inline PIByteArray & push_back(std::initializer_list init_list) { + d.push_back(init_list); + return *this; + } + + //! \~english Appends the given array `v` to the end of the array. + //! \~russian Добавляет массив `v` в конец массива. + //! \~\details + //! \~english Overloaded function. + //! \~russian Перегруженая функция. + //! \~\sa \a push_back() + inline PIByteArray & push_back(const PIByteArray & v) { + d.push_back(v.d); + return *this; + } + + + //! \~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;} + + //! \~english Appends the given element `e` to the begin of the array. + //! \~russian Добавляет элемент `e` в начало массива. + //! \~\details + //! \~english If there is free space at the beginning of the array, + //! which is most often, then the addition will be very fast. + //! In any case, the addition is fast and does not depend on the size of the array. + //! If there is no free space at the beginning of the array + //! then all iterators and references + //! (including the past-the-begin iterator) are invalidated. + //! Otherwise only the past-the-begin iterator is invalidated. + //! \~russian Если в начале массива имеется свободное место, + //! что часто бывает, то добавление будет очень быстрым. + //! В любом случае добавление быстрое и не зависит от размера массива. + //! Если в начале массива нет свободного места, + //! то все итераторы и указатели становятся нерабочими. + //! В противном случае все, кроме итераторов указывающих, на начало массива, + //! остаются в рабочем состоянии. + //! \~\sa \a push_back(), \a append(), \a prepend(), \a insert() + inline PIByteArray & push_front(uchar e) { + d.push_front(e); + return *this; + } + + //! \~english Appends the given array `v` to the begin of the array. + //! \~russian Добавляет массив `v` в начало массива. + //! \~\details + //! \~english Overloaded function. + //! \~russian Перегруженая функция. + //! \~\sa \a push_front() + inline PIByteArray & push_front(const PIByteArray & v) { + d.push_front(v.d); + return *this; + } + + //! \~english Appends the given elements to the begin of the array. + //! \~russian Добавляет элементы в начало массива. + //! \~\details + //! \~english Overloaded function. + //! Appends the given elements from + //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian Перегруженая функция. + //! Добавляет элементы из + //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). + //! \~\sa \a append() + inline PIByteArray & push_front(std::initializer_list init_list) { + d.push_front(init_list); + return *this; + } + + //! \~english Appends the given element `e` to the begin of the array. + //! \~russian Добавляет элемент `e` в начало массива. + //! \~\details + //! \~english If there is free space at the beginning of the array, + //! which is most often, then the addition will be very fast. + //! In any case, the addition is fast and does not depend on the size of the array. + //! If there is no free space at the beginning of the array + //! then all iterators and references + //! (including the past-the-begin iterator) are invalidated. + //! Otherwise only the past-the-begin iterator is invalidated. + //! \~russian Если в начале массива имеется свободное место, + //! что часто бывает, то добавление будет очень быстрым. + //! В любом случае добавление быстрое и не зависит от размера массива. + //! Если в начале массива нет свободного места, + //! то все итераторы и указатели становятся нерабочими. + //! В противном случае все, кроме итераторов указывающих, на начало массива, + //! остаются в рабочем состоянии. + //! \~\sa \a push_back(), \a append(), \a prepend(), \a insert() + inline PIByteArray & prepend(uchar e) { + d.prepend(e); + return *this; + } + + //! \~english Appends the given array `v` to the begin of the array. + //! \~russian Добавляет массив `v` в начало массива. + //! \~\details + //! \~english Overloaded function. + //! \~russian Перегруженая функция. + //! \~\sa \a prepend() + inline PIByteArray & prepend(const PIByteArray & v) { + d.prepend(v.d); + return *this; + } + + //! \~english Appends the given elements to the begin of the array. + //! \~russian Добавляет элементы в начало массива. + //! \~\details + //! \~english Overloaded function. + //! Appends the given elements from + //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian Перегруженая функция. + //! Добавляет элементы из + //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). + //! \~\sa \a append() + inline PIByteArray & prepend(std::initializer_list init_list) { + d.prepend(init_list); + return *this; + } + + //! \~english Remove one element from the end of the array. + //! \~russian Удаляет один элемент с конца массива. + //! \~\details + //! \~english Deleting an element from the end is very fast + //! and does not depend on the size of the array. + //! \~russian Удаление элемента с конца выполняется очень быстро + //! и не зависит от размера массива. + //! \~\sa \a pop_front(), \a take_back(), \a take_front() + inline PIByteArray & pop_back() { + d.pop_back(); + return *this; + } + + //! \~english Remove one element from the begining of the array. + //! \~russian Удаляет один элемент с начала массива. + //! \~\details + //! \~english Removing an element from the beginning takes longer than from the end. + //! This time is directly proportional to the size of the array. + //! All iterators and references are invalidated. + //! \~russian Удаление элемента с начала выполняется дольше, чем с конца. + //! Это время прямопропорционально размеру массива. + //! При удалении элемента все итераторы и указатели становятся нерабочими. + //! \~\sa \a pop_back(), \a take_back(), \a take_front() + inline PIByteArray & pop_front() { + d.pop_front(); + return *this; + } + + //! \~english Remove one element from the end of the array and return it. + //! \~russian Удаляет один элемент с начала массива и возвращает его. + //! \~\details + //! \~\sa \a take_front(), \a pop_back(), \a pop_front() + 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(); + } + + //! \~english Returns a new array with all elements + //! that pass the test implemented by the provided function `test`. + //! \~russian Возвращает новый массив со всеми элементами, + //! прошедшими проверку, задаваемую в передаваемой функции `test`. + //! \~\details + //! \~\code + //! PIByteArray v{3, 2, 5, 2, 7}; + //! PIByteArray v2 = v.filter([](const uchar & i){return i > 2;}); + //! piCout << v2; // {3, 5, 7} + //! \endcode + //! \~\sa \a map(), \a any(), \a every() + inline PIByteArray filter(std::function 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)` для каждого элемента массива. + //! \~\details + //! \~russian Не позволяет изменять элементы массива. + //! Для редактирования элементов используйте функцию вида `void f(uchar & e)`. + //! \~english Does not allow changing array elements. + //! To edit elements, use the function like `void f(T & e)` + //! \~\code + //! PIByteArray v{1, 2, 3, 4, 5}; + //! int s = 0; + //! v.forEach([&s](const uchar & e){s += e;}); + //! piCout << s; // 15 + //! \endcode + //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() + inline void forEach(std::function f) const { + d.forEach(f); + } + + //! \~english Execute function `void f(uchar & e)` for every element in array. + //! \~russian Выполняет функцию `void f(uchar & e)` для каждого элемента массива. + //! \~\details + //! \~english Overloaded function. + //! Allows you to change the elements of the array. + //! \~russian Перегруженая функция. + //! Позволяет изменять элементы массива. + //! \~\code + //! PIByteArray v{1, 2, 3, 4, 5}; + //! v.forEach([](uchar & e){e++;}); + //! piCout << v; // {2, 3, 4, 5, 6} + //! \endcode + //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() + inline PIByteArray & forEach(std::function f) { + d.forEach(f); + return *this; + } + + //! \~english Сreates a new array populated with the results + //! of calling a provided function `ST f(const uchar & e)` on every element in the calling array. + //! \~russian Создаёт новый массив с результатом вызова указанной функции + //! `ST f(const T & e)` для каждого элемента массива. + //! \~\details + //! \~english Calls a provided function`ST f(const uchar & e)` + //! once for each element in an array, in order, + //! and constructs a new array from the results. + //! \~russian Метод `map` вызывает переданную функцию `ST f(const uchar & e)` + //! один раз для каждого элемента в порядке их появления + //! и конструирует новый массив из результатов её вызова. + //! \~\code + //! PIByteArray v{0x31, 0x0A, 0xFF}; + //! PIStringList sl = v.map([](const uchar & i){return PIString::fromNumber(i, 16);}); + //! piCout << sl; {"31", "A", "FF"} + //! \endcode + //! \~\sa \a forEach(), \a reduce() + template + inline PIDeque map(std::function f) const { + return d.map(f); + } + + //! \~english Applies the function `ST f(const uchar & e, const ST & acc)` + //! to each element of the array (from left to right), returns one value. + //! \~russian Применяет функцию `ST f(const uchar & e, const ST & acc)` + //! к каждому элементу массива (слева-направо), возвращает одно значение. + //! \~\details + //! \~english The reduce() method performs the `f` function + //! once for each element in the array. + //! If the `initial` argument is passed when calling reduce(), + //! then when the function `f` is called for the first time, + //! the value of `acc` will be assigned to `initial`. + //! If the array is empty, the value `initial` will be returned. + //! \param f is a function like `ST f(const uchar & e, const ST & acc)`, + //! executed for each element of the array. It takes two arguments: + //! * **e** - current element of the array + //! * **acc** - accumulator accumulating the value + //! which this function returns after visiting the next element + //! + //! \param initial _optional_ Object used as the second argument + //! when the `f` function is first called. + //! \~russian Метод reduce() выполняет функцию `f` + //! один раз для каждого элемента, присутствующего в массиве. + //! Если при вызове reduce() передан аргумент `initial`, + //! то при первом вызове функции `f` значение `acc` + //! будет равным значению `initial`. + //! Если массив пустой то будет возвращено значение `initial`. + //! \param f Функция, вида `ST f(const uchar & e, const ST & acc)`, + //! выполняющаяся для каждого элемента массива. + //! Она принимает два аргумента: + //! * **e** - текущий элемент массива + //! * **acc** - аккумулятор, аккумулирующий значение + //! которое возвращает эта функция после посещения очередного элемента + //! + //! \param initial _опциональный_ Объект, + //! используемый в качестве второго аргумента при первом вызове функции `f`. + //! + //! \~\code + //! PIByteArray v{1, 2, 3, 4, 5}; + //! PIString s = v.reduce([](const uchar & e, const PIString & acc){return acc + PIString::fromNumber(e);}); + //! piCout << s; // "12345" + //! \endcode + //! \~\sa \a forEach(), \a map() + template + inline ST reduce(std::function f, const ST & initial = ST()) const { + return d.reduce(f, initial); + } + + //! \~english Convert data to Base 64 and return this byte array + //! \~russian Преобразует данные в Base 64 и возвращает текущий массив + PIByteArray & convertToBase64(); + + //! \~english Convert data from Base 64 and return this byte array + //! \~russian Преобразует данные из Base 64 и возвращает текущий массив + PIByteArray & convertFromBase64(); + + //! \~english Return converted to Base 64 data + //! \~russian Возвращает копию байтового массива, преобразованного в Base 64 + PIByteArray toBase64() const; + + 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;} + + //! \~english Return string representation of data, each byte in "base" base, separated by spaces + //! \~russian Возвращает текстовое представление байтового массива, каждый байт в "base" системе, с пробелами + PIString toString(int base = 16) const; + + //! \~english + //! Returns a hex encoded copy of the byte array, without spaces. + //! The hex encoding uses the numbers 0-9 and the letters a-f. + //! \~russian + //! Возвращает шестнадцатеричное представление массива, без пробелов. + //! Оно использует цифры 0-9 и буквы a-f. + PIString toHex() const; + + //! \~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;} + + //! \~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;} + + //! \~english Add to the end "t" + //! \~russian Добавляет в конец массива байт "t" + PIByteArray & append(uchar t) {push_back(t); return *this;} + + //! \~english Appends the given elements to the end of the array. + //! \~russian Добавляет элементы в конец массива. + //! \~\details + //! \~english Overloaded function. + //! Appends the given elements from + //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian Перегруженая функция. + //! Добавляет элементы из + //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). + //! \~\sa \a push_back() + inline PIByteArray & append(std::initializer_list init_list) { + d.append(init_list); + return *this; + } + + //! \~english Returns 8-bit checksum + //! \~russian Возвращает 8-битную контрольную сумму + uchar checksumPlain8(bool inverse = true) const; + + //! \~english Returns 32-bit checksum + //! \~russian Возвращает 32-битную контрольную сумму + uint checksumPlain32(bool inverse = true) const; + + //! \~english Returns 8-bit checksum CRC-8 + //! \~russian Возвращает 8-битную контрольную сумму CRC-8 + uchar checksumCRC8() const; + + //! \~english Returns 16-bit checksum CRC-16 + //! \~russian Возвращает 16-битную контрольную сумму CRC-16 + ushort checksumCRC16() const; + + //! \~english Returns 32-bit checksum CRC-32 + //! \~russian Возвращает 32-битную контрольную сумму CRC-32 + uint checksumCRC32() const; + + //! \~english Returns hash of content + //! \~russian Возвращает хэш содержимого + uint hash() const; + + void operator =(const PIDeque & 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 =(PIByteArray && o) {swap(o); return *this;} + + static PIByteArray fromUserInput(PIString str); + + static PIByteArray fromHex(PIString str); + + //! \~english Return converted from Base 64 data + //! \~russian Возвращает массив из Base 64 представления + static PIByteArray fromBase64(const PIByteArray & base64); + static PIByteArray fromBase64(const PIString & base64); + + + bool binaryStreamAppendImp(const void * d_, size_t s) { + append(d_, s); + return true; + } + bool binaryStreamTakeImp(void * d_, size_t s) { + size_t rs = size(); + if (rs > s) rs = s; + memcpy(d_, data(), rs); + remove(0, rs); + return rs == s; + } + + ssize_t binaryStreamSizeImp() const {return size();} + +private: + PIDeque d; + +}; + +//! \relatesalso PIByteArray +//! \~english Byte arrays compare operator +//! \~russian Оператор сравнения +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; + } + return v0.size() < v1.size(); +} + +//! \relatesalso PIByteArray +//! \~english Byte arrays compare operator +//! \~russian Оператор сравнения +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; + } + return v0.size() > v1.size(); +} + +//! \relatesalso PIByteArray +//! \~english Byte arrays compare operator +//! \~russian Оператор сравнения +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; + } + return false; +} + +//! \relatesalso PIByteArray +//! \~english Byte arrays compare operator +//! \~russian Оператор сравнения +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; + } + return true; +} + +#ifdef PIP_STD_IOSTREAM +//! \relatesalso PIByteArray \brief Output to std::ostream operator +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); + + +//! \relatesalso PIBinaryStream +//! \~english Store operator. +//! \~russian Оператор сохранения. +BINARY_STREAM_WRITE(PIByteArray) { + s.binaryStreamAppend((int)v.size_s()); + s.binaryStreamAppend(v.data(), v.size()); + return s; +} + +//! \relatesalso PIBinaryStream +//! \~english Restore operator. +//! \~russian Оператор извлечения. +BINARY_STREAM_READ(PIByteArray) { + v.resize(s.binaryStreamTakeInt()); + s.binaryStreamTake(v.data(), v.size()); + return s; +} + + +//! \relatesalso PIByteArray +//! \~english Returns PIByteArray::hash() of "ba" +//! \~russian Возвращает PIByteArray::hash() от "ba" +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);} + + +//! \relatesalso PIByteArray +//! \~english Store "value" to bytearray and returns it +//! \~russian Сохраняет "value" в байтовый массив и возвращает его +template PIByteArray piSerialize(const T & value) { + PIByteArray ret; + ret << value; + return ret; +} + +//! \relatesalso PIByteArray +//! \~english Restore type "T" from bytearray "data" and returns it +//! \~russian Извлекает тип "T" из байтового массива "data" и возвращает его +template T piDeserialize(const PIByteArray & data) { + T ret; + if (!data.isEmpty()) { + PIByteArray ba(data); + ba >> ret; + } + return ret; +} + + +#endif // PIBYTEARRAY_H diff --git a/libs/main/core/pidatetime.cpp b/libs/main/types/pidatetime.cpp similarity index 99% rename from libs/main/core/pidatetime.cpp rename to libs/main/types/pidatetime.cpp index f8b004aa..bab5d856 100644 --- a/libs/main/core/pidatetime.cpp +++ b/libs/main/types/pidatetime.cpp @@ -33,7 +33,7 @@ # include #endif -//! \addtogroup Core +//! \addtogroup Types //! \{ //! //! \~\class PITime pidatetime.h diff --git a/libs/main/core/pidatetime.h b/libs/main/types/pidatetime.h similarity index 99% rename from libs/main/core/pidatetime.h rename to libs/main/types/pidatetime.h index c5da3208..6d23a7e9 100644 --- a/libs/main/core/pidatetime.h +++ b/libs/main/types/pidatetime.h @@ -1,5 +1,5 @@ /*! \file pidatetime.h - * \ingroup Core + * \ingroup Types * \~\brief * \~english Time and date structs * \~russian Типы времени и даты @@ -30,7 +30,7 @@ #include "pisystemtime.h" -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english Calendar time. //! \~russian Календарное время. @@ -106,7 +106,7 @@ PIP_EXPORT PICout operator <<(PICout s, const PITime & v); -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english Calendar date. //! \~russian Календарная дата. @@ -170,7 +170,7 @@ PIP_EXPORT PICout operator <<(PICout s, const PIDate & v); -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english Calendar date and time. //! \~russian Календарное дата и время. diff --git a/libs/main/core/piflags.h b/libs/main/types/piflags.h similarity index 99% rename from libs/main/core/piflags.h rename to libs/main/types/piflags.h index 4d1f886e..399ed812 100644 --- a/libs/main/core/piflags.h +++ b/libs/main/types/piflags.h @@ -1,5 +1,5 @@ /*! \file piflags.h - * \ingroup Core + * \ingroup Types * \~\brief * \~english General flags class * \~russian Универсальные флаги @@ -28,7 +28,7 @@ #include "pip_export.h" -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\class PIFlags piflags.h //! \~\brief diff --git a/libs/main/core/pipropertystorage.cpp b/libs/main/types/pipropertystorage.cpp similarity index 100% rename from libs/main/core/pipropertystorage.cpp rename to libs/main/types/pipropertystorage.cpp diff --git a/libs/main/core/pipropertystorage.h b/libs/main/types/pipropertystorage.h similarity index 99% rename from libs/main/core/pipropertystorage.h rename to libs/main/types/pipropertystorage.h index 6649ec3f..bf11ffcf 100644 --- a/libs/main/core/pipropertystorage.h +++ b/libs/main/types/pipropertystorage.h @@ -1,5 +1,5 @@ /*! \file pipropertystorage.h - * \ingroup Core + * \ingroup Types * \~\brief * \~english Properties array * \~russian Массив свойств @@ -29,7 +29,7 @@ #include "pivariant.h" -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english This class provides key-value properties storage. //! \~russian Этот класс предоставляет ключ-значение хранение свойств. @@ -40,7 +40,7 @@ public: //! \~russian Создает пустой %PIPropertyStorage PIPropertyStorage() {} - //! \ingroup Core + //! \ingroup Types //! \~\brief //! \~english PIPropertyStorage element. //! \~russian Элемент PIPropertyStorage. diff --git a/libs/main/core/pisystemtime.cpp b/libs/main/types/pisystemtime.cpp similarity index 100% rename from libs/main/core/pisystemtime.cpp rename to libs/main/types/pisystemtime.cpp diff --git a/libs/main/core/pisystemtime.h b/libs/main/types/pisystemtime.h similarity index 99% rename from libs/main/core/pisystemtime.h rename to libs/main/types/pisystemtime.h index e3653db5..aeb6a37f 100644 --- a/libs/main/core/pisystemtime.h +++ b/libs/main/types/pisystemtime.h @@ -1,5 +1,5 @@ /*! \file pisystemtime.h - * \ingroup Core + * \ingroup Types * \~\brief * \~english System time structs and methods * \~russian Типы и методы системного времени @@ -30,7 +30,7 @@ #include "pistring.h" -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english System time with nanosecond precision. //! \~russian Системное время с точностью до наносекунд. @@ -191,7 +191,7 @@ inline PICout operator <<(PICout s, const PISystemTime & v) {s.space(); s.saveAn -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english Time measurements. //! \~russian Измерение времени. diff --git a/libs/main/core/pitime.cpp b/libs/main/types/pitime.cpp similarity index 100% rename from libs/main/core/pitime.cpp rename to libs/main/types/pitime.cpp diff --git a/libs/main/core/pitime.h b/libs/main/types/pitime.h similarity index 95% rename from libs/main/core/pitime.h rename to libs/main/types/pitime.h index 29c36005..f794e9bf 100644 --- a/libs/main/core/pitime.h +++ b/libs/main/types/pitime.h @@ -1,5 +1,5 @@ /*! \file pitime.h - * \ingroup Core + * \ingroup Types * \~\brief * \~english System time, time and date * \~russian Системное время, время и дата @@ -27,12 +27,12 @@ #include "pidatetime.h" -//! \ingroup Core +//! \ingroup Types //! \~english Precise sleep for "usecs" microseconds //! \~russian Точно ожидает "usecs" микросекунд PIP_EXPORT void piUSleep(int usecs); // on !Windows consider constant "usleep" offset -//! \ingroup Core +//! \ingroup Types //! \brief //! \~english Precise sleep for "msecs" milliseconds //! \~russian Точно ожидает "msecs" миллисекунд @@ -41,7 +41,7 @@ PIP_EXPORT void piUSleep(int usecs); // on !Windows consider constant "usleep" o //! \~russian Этот метод вызывает \a piUSleep (msecs * 1000) inline void piMSleep(double msecs) {piUSleep(int(msecs * 1000.));} // on !Windows consider constant "usleep" offset -//! \ingroup Core +//! \ingroup Types //! \brief //! \~english Precise sleep for "secs" seconds //! \~russian Точно ожидает "secs" секунд @@ -50,7 +50,7 @@ inline void piMSleep(double msecs) {piUSleep(int(msecs * 1000.));} // on !Window //! \~russian Этот метод вызывает \a piUSleep (msecs * 1000000) inline void piSleep(double secs) {piUSleep(int(secs * 1000000.));} // on !Windows consider constant "usleep" offset -//! \ingroup Core +//! \ingroup Types //! \~english Shortest available on current system sleep //! \~russian Наименее возможное для данной системы по длительности ожидание inline void piMinSleep() {piMSleep(PIP_MIN_MSLEEP);} diff --git a/libs/main/core/pitime_win.h b/libs/main/types/pitime_win.h similarity index 99% rename from libs/main/core/pitime_win.h rename to libs/main/types/pitime_win.h index 80aedd7f..6e7d7fd4 100644 --- a/libs/main/core/pitime_win.h +++ b/libs/main/types/pitime_win.h @@ -1,5 +1,5 @@ /*! \file pitime_win.h - * \ingroup Core + * \ingroup Types * \brief * \~english PITime conversions for Windows * \~russian Преобразования PITime для Windows diff --git a/libs/main/types/pitypesmodule.h b/libs/main/types/pitypesmodule.h new file mode 100644 index 00000000..66ccf775 --- /dev/null +++ b/libs/main/types/pitypesmodule.h @@ -0,0 +1,61 @@ +/* + 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 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 . +*/ +//! \defgroup Types Types +//! \~\brief +//! \~english Basic types. +//! \~russian Базовые типы. +//! +//! \~\details +//! \~english \section cmake_module_Types Building with CMake +//! \~russian \section cmake_module_Types Сборка с использованием CMake +//! +//! \~\code +//! find_package(PIP REQUIRED) +//! target_link_libraries([target] PIP) +//! \endcode +//! +//! \~english \par Common +//! \~russian \par Общее +//! +//! \~english +//! +//! +//! \~russian +//! +//! +//! \~\authors +//! \~english +//! Ivan Pelipenko peri4ko@yandex.ru; +//! Andrey Bychkov work.a.b@yandex.ru; +//! \~russian +//! Иван Пелипенко peri4ko@yandex.ru; +//! Андрей Бычков work.a.b@yandex.ru; +//! + +#ifndef PITYPESMODULE_H +#define PITYPESMODULE_H + +#include "pibitarray.h" +#include "pibytearray.h" +#include "piflags.h" +#include "pitime.h" +#include "pipropertystorage.h" +#include "pivariantsimple.h" + +#endif // PITYPESMODULE_H diff --git a/libs/main/core/pivariant.cpp b/libs/main/types/pivariant.cpp similarity index 100% rename from libs/main/core/pivariant.cpp rename to libs/main/types/pivariant.cpp diff --git a/libs/main/core/pivariant.h b/libs/main/types/pivariant.h similarity index 99% rename from libs/main/core/pivariant.h rename to libs/main/types/pivariant.h index c3ab9af8..f14295b4 100644 --- a/libs/main/core/pivariant.h +++ b/libs/main/types/pivariant.h @@ -1,5 +1,5 @@ /*! \file pivariant.h - * \ingroup Core + * \ingroup Types * \brief * \~english Variant type * \~russian Вариативный тип @@ -218,7 +218,7 @@ classname_to __PIVariantFunctions__::castVariant(c #endif -//! \ingroup Core +//! \ingroup Types //! \~\brief //! \~english Variant type. //! \~russian Вариантный тип. diff --git a/libs/main/core/pivariantsimple.h b/libs/main/types/pivariantsimple.h similarity index 99% rename from libs/main/core/pivariantsimple.h rename to libs/main/types/pivariantsimple.h index cdd14fa8..3b60bc48 100644 --- a/libs/main/core/pivariantsimple.h +++ b/libs/main/types/pivariantsimple.h @@ -1,5 +1,5 @@ /*! \file pivariantsimple.h - * \ingroup Core + * \ingroup Types * \brief * \~english Simple variant type * \~russian Простой вариативный тип @@ -62,7 +62,7 @@ public: }; -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\class PIVariantSimple pivariantsimple.h //! \~\brief diff --git a/libs/main/core/pivarianttypes.cpp b/libs/main/types/pivarianttypes.cpp similarity index 100% rename from libs/main/core/pivarianttypes.cpp rename to libs/main/types/pivarianttypes.cpp diff --git a/libs/main/core/pivarianttypes.h b/libs/main/types/pivarianttypes.h similarity index 98% rename from libs/main/core/pivarianttypes.h rename to libs/main/types/pivarianttypes.h index 8c8bcd04..82bb7e14 100644 --- a/libs/main/core/pivarianttypes.h +++ b/libs/main/types/pivarianttypes.h @@ -1,5 +1,5 @@ /*! \file pivarianttypes.h - * \ingroup Core + * \ingroup Types * \brief * \~english Types for PIVariant * \~russian Типы для PIVariant @@ -32,14 +32,14 @@ class PIPropertyStorage; -//! \ingroup Core +//! \ingroup Types //! \relatesalso PIVariant //! \~english Namespace contains several types for PIVariant //! \~russian Пространство имен содержит некоторые типы для PIVariant namespace PIVariantTypes { -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\struct Enumerator pivarianttypes.h //! \~\brief @@ -59,7 +59,7 @@ struct PIP_EXPORT Enumerator { }; -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\struct Enum pivarianttypes.h //! \~\brief @@ -165,7 +165,7 @@ struct PIP_EXPORT Enum { }; -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\struct File pivarianttypes.h //! \~\brief @@ -198,7 +198,7 @@ struct PIP_EXPORT File { }; -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\struct Dir pivarianttypes.h //! \~\brief @@ -223,7 +223,7 @@ struct PIP_EXPORT Dir { }; -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\struct Color pivarianttypes.h //! \~\brief @@ -239,7 +239,7 @@ struct PIP_EXPORT Color { }; -//! \addtogroup Core +//! \addtogroup Types //! \{ //! \~\struct IODevice pivarianttypes.h //! \~\brief