diff --git a/CMakeLists.txt b/CMakeLists.txt index efb7d041..bebf884d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,8 +2,8 @@ cmake_minimum_required(VERSION 3.0) cmake_policy(SET CMP0017 NEW) # need include() with .cmake project(pip) set(pip_MAJOR 2) -set(pip_MINOR 94) -set(pip_REVISION 1) +set(pip_MINOR 95) +set(pip_REVISION 0) set(pip_SUFFIX ) set(pip_COMPANY SHS) set(pip_DOMAIN org.SHS) diff --git a/libs/main/core/pibytearray.cpp b/libs/main/core/pibytearray.cpp index c589e584..639a86db 100644 --- a/libs/main/core/pibytearray.cpp +++ b/libs/main/core/pibytearray.cpp @@ -28,14 +28,14 @@ //! It can be constructed from any data and size. //! You can use %PIByteArray as binary stream //! to serialize/deserialize any objects and data. -//! This class based on PIDeque and provide some handle function +//! This class use PIDeque and provide some handle function //! to manipulate it. //! \~russian //! %PIByteArray используется для хранения байтов. //! Он может быть сконструирован из любых даных. //! Можно использовать %PIByteArray как потоковый объект //! для сериализации/десериализации любых типов и данных. -//! Этот класс наследован от PIDeque и предоставляет набор +//! Этот класс использует PIDeque и предоставляет набор //! удобных методов для работы с байтами. //! //! \~english \section PIByteArray_sec0 Usage diff --git a/libs/main/core/pibytearray.h b/libs/main/core/pibytearray.h index 9a4aed33..940c1651 100644 --- a/libs/main/core/pibytearray.h +++ b/libs/main/core/pibytearray.h @@ -38,24 +38,24 @@ class PIByteArray; //! \~\brief //! \~english The %PIByteArray class provides an array of bytes. //! \~russian Класс %PIByteArray представляет собой массив байтов. -class PIP_EXPORT PIByteArray: public PIDeque, public PIBinaryStream +class PIP_EXPORT PIByteArray: public PIBinaryStream { public: typedef ::PIMemoryBlock RawData DEPRECATEDM("use PIMemoryBlock instead"); //! \~english Constructs an empty byte array //! \~russian Создает пустой байтовый массив - PIByteArray() {;} + PIByteArray() {} //! \~english Constructs copy of byte array "o" //! \~russian Создает копию байтового массива "o" - PIByteArray(const PIByteArray & o): PIDeque(o) {} + PIByteArray(const PIByteArray & o): d(o.d) {} //! \~english Constructs copy of byte array "o" //! \~russian Создает копию байтового массива "o" - PIByteArray(const PIDeque & o): PIDeque(o) {} + PIByteArray(const PIDeque & o): d(o) {} - PIByteArray(PIByteArray && o): PIDeque(std::move(o)) {} + PIByteArray(PIByteArray && o): d(std::move(o.d)) {} //! \~english Constructs 0-filled byte array with size "size" //! \~russian Создает заполненный "0" байтовый массив размером "size" @@ -63,23 +63,664 @@ public: //! \~english Constructs byte array from data "data" and size "size" //! \~russian Создает байтовый массив из данных по указателю "data" размером "size" - PIByteArray(const void * data, const uint size): PIDeque((const uchar*)data, size_t(size)) {} + PIByteArray(const void * data, const uint size): d((const uchar*)data, size_t(size)) {} //! \~english Constructs byte array with size "size" filled by "t" //! \~russian Создает заполненный "t" байтовый массив размером "size" - PIByteArray(const uint size, uchar t): PIDeque(size, t) {} + PIByteArray(const uint size, uchar t): d(size, t) {} + //! \~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 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 + //! PIDeque 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() + 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() + inline int entries(std::function test, ssize_t start = 0) const { + return d.entries(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 PIDeque::getRange(index, count); + 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(llong add_size) { + d.enlarge(add_size); + 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 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 Convert data to Base 64 and return this byte array //! \~russian Преобразует данные в Base 64 и возвращает текущий массив @@ -134,7 +775,7 @@ public: //! \~russian Возвращает хэш содержимого uint hash() const; - void operator =(const PIDeque & d) {resize(d.size()); memcpy(data(), d.data(), d.size());} + 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;} @@ -150,18 +791,21 @@ public: static PIByteArray fromBase64(const PIString & base64); - bool binaryStreamAppendImp(const void * d, size_t s) { - append(d, s); + bool binaryStreamAppendImp(const void * d_, size_t s) { + append(d_, s); return true; } - bool binaryStreamTakeImp(void * d, size_t s) { + bool binaryStreamTakeImp(void * d_, size_t s) { if (size() < s) return false; - memcpy(d, data(), s); + memcpy(d_, data(), s); remove(0, s); return true; } +private: + PIDeque d; + }; //! \relatesalso PIByteArray