From e1b89aeca8ee9f9abc7896b8b8cf722cc690eb36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=91=D1=8B=D1=87=D0=BA=D0=BE=D0=B2=20=D0=90=D0=BD=D0=B4?= =?UTF-8?q?=D1=80=D0=B5=D0=B9?= Date: Mon, 25 Jul 2022 10:07:48 +0300 Subject: [PATCH] PIByteArray begin end indexOf map reduce forEach PIVector and PIDeque small fixes --- libs/main/containers/pideque.h | 16 +- libs/main/containers/pivector.h | 14 +- libs/main/core/pibytearray.h | 362 +++++++++++++++++++++++++++++++- 3 files changed, 366 insertions(+), 26 deletions(-) diff --git a/libs/main/containers/pideque.h b/libs/main/containers/pideque.h index a90b6419..8c5878b9 100644 --- a/libs/main/containers/pideque.h +++ b/libs/main/containers/pideque.h @@ -645,7 +645,7 @@ public: inline size_t length() const {return pid_size;} //! \~english Number of elements that the container has currently allocated space for. - //! \~russian Количество элементов, для которого сейчас выделена память контейнером. + //! \~russian Количество элементов, для которого сейчас выделена память массивом. //! \~\details //! \~english To find out the actual number of items, use the function \a size(). //! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size(). @@ -655,18 +655,18 @@ public: inline size_t _start() const {return pid_start;} //! \~english Checks if the container has no elements. - //! \~russian Проверяет пуст ли контейнер. + //! \~russian Проверяет пуст ли массив. //! \~\return //! \~english **true** if the container is empty, **false** otherwise - //! \~russian **true** если контейнер пуст, **false** иначе. + //! \~russian **true** если массив пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isEmpty() const {return (pid_size == 0);} //! \~english Checks if the container has elements. - //! \~russian Проверяет не пуст ли контейнер. + //! \~russian Проверяет не пуст ли массив. //! \~\return //! \~english **true** if the container is not empty, **false** otherwise - //! \~russian **true** если контейнер не пуст, **false** иначе. + //! \~russian **true** если массив не пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isNotEmpty() const {return (pid_size > 0);} @@ -1572,10 +1572,10 @@ public: //! Если `add_size < 0`, то с конца массива удаляются элементы. //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. //! \~\sa \a resize() - inline PIDeque & enlarge(llong pid_size) { - llong ns = size_s() + pid_size; + inline PIDeque & enlarge(ssize_t add_size, const T & e = T()) { + ssize_t ns = size_s() + add_size; if (ns <= 0) clear(); - else resize(size_t(ns)); + else resize(size_t(ns), e); return *this; } diff --git a/libs/main/containers/pivector.h b/libs/main/containers/pivector.h index c9dff3c1..4a01319b 100644 --- a/libs/main/containers/pivector.h +++ b/libs/main/containers/pivector.h @@ -645,7 +645,7 @@ public: inline size_t length() const {return piv_size;} //! \~english Number of elements that the container has currently allocated space for. - //! \~russian Количество элементов, для которого сейчас выделена память контейнером. + //! \~russian Количество элементов, для которого сейчас выделена память массивом. //! \~\details //! \~english To find out the actual number of items, use the function \a size(). //! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size(). @@ -653,18 +653,18 @@ public: inline size_t capacity() const {return piv_rsize;} //! \~english Checks if the container has no elements. - //! \~russian Проверяет пуст ли контейнер. + //! \~russian Проверяет пуст ли массив. //! \~\return //! \~english **true** if the container is empty, **false** otherwise - //! \~russian **true** если контейнер пуст, **false** иначе. + //! \~russian **true** если массив пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isEmpty() const {return (piv_size == 0);} //! \~english Checks if the container has elements. - //! \~russian Проверяет не пуст ли контейнер. + //! \~russian Проверяет не пуст ли массив. //! \~\return //! \~english **true** if the container is not empty, **false** otherwise - //! \~russian **true** если контейнер не пуст, **false** иначе. + //! \~russian **true** если массив не пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isNotEmpty() const {return (piv_size > 0);} @@ -1512,8 +1512,8 @@ public: //! Если `add_size < 0`, то с конца массива удаляются элементы. //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. //! \~\sa \a resize() - inline PIVector & enlarge(llong add_size, const T & e = T()) { - llong ns = size_s() + add_size; + inline PIVector & enlarge(ssize_t add_size, const T & e = T()) { + ssize_t ns = size_s() + add_size; if (ns <= 0) clear(); else resize(size_t(ns), e); return *this; diff --git a/libs/main/core/pibytearray.h b/libs/main/core/pibytearray.h index 940c1651..44acc974 100644 --- a/libs/main/core/pibytearray.h +++ b/libs/main/core/pibytearray.h @@ -69,6 +69,16 @@ public: //! \~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` с этим массивом. @@ -79,6 +89,62 @@ public: 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() @@ -95,7 +161,7 @@ public: inline size_t length() const {return d.length();} //! \~english Number of elements that the container has currently allocated space for. - //! \~russian Количество элементов, для которого сейчас выделена память контейнером. + //! \~russian Количество элементов, для которого сейчас выделена память массивом. //! \~\details //! \~english To find out the actual number of items, use the function \a size(). //! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size(). @@ -103,18 +169,18 @@ public: inline size_t capacity() const {return d.capacity();} //! \~english Checks if the container has no elements. - //! \~russian Проверяет пуст ли контейнер. + //! \~russian Проверяет пуст ли массив. //! \~\return //! \~english **true** if the container is empty, **false** otherwise - //! \~russian **true** если контейнер пуст, **false** иначе. + //! \~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 Проверяет не пуст ли контейнер. + //! \~russian Проверяет не пуст ли массив. //! \~\return //! \~english **true** if the container is not empty, **false** otherwise - //! \~russian **true** если контейнер не пуст, **false** иначе. + //! \~russian **true** если массив не пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isNotEmpty() const {return d.isNotEmpty();} @@ -219,7 +285,7 @@ public: //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. //! \~\code - //! PIDeque v{1, 2, 3, 4}; + //! PIByteArray v{1, 2, 3, 4}; //! piCout << v.contains(3); // true //! piCout << v.contains(5); // false //! piCout << v.contains(3, 3); // false @@ -254,7 +320,7 @@ public: //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. - //! \~\sa \a every(), \a any(), \a contains() + //! \~\sa \a every(), \a any(), \a contains(), \a indexOf() inline int entries(uchar e, ssize_t start = 0) const { return d.entries(e, start); } @@ -280,11 +346,143 @@ public: //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. - //! \~\sa \a every(), \a any(), \a contains() + //! \~\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 @@ -384,7 +582,11 @@ public: //! \~english Return resized byte array //! \~russian Возвращает копию байтового массива с измененным размером - PIByteArray resized(uint new_size) const {PIByteArray ret(new_size); memcpy(ret.data(), data(), new_size); return ret;} + 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` элементов. @@ -496,8 +698,8 @@ public: //! Если `add_size < 0`, то с конца массива удаляются элементы. //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. //! \~\sa \a resize() - inline PIByteArray & enlarge(llong add_size) { - d.enlarge(add_size); + inline PIByteArray & enlarge(ssize_t add_size, uchar e = 0) { + d.enlarge(add_size, e); return *this; } @@ -580,6 +782,10 @@ public: } + //! \~english Add to the end data "data" with size "size" + //! \~russian Добавляет в конец массива данные по указателю "data" размером "size" + PIByteArray & push_back(const void * data_, int size_) {uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this;} + //! \~english Appends the given element `e` to the begin of the array. //! \~russian Добавляет элемент `e` в начало массива. //! \~\details @@ -722,6 +928,125 @@ public: 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(); @@ -763,6 +1088,21 @@ public: //! \~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;