From 96c22e118483f031186291dd87821b4d1c4ab569 Mon Sep 17 00:00:00 2001 From: "andrey.bychkov" Date: Fri, 20 Mar 2026 16:31:30 +0300 Subject: [PATCH] move std function --- libs/http_client/pihttpclient.cpp | 6 +- libs/http_server/pihttpserver.cpp | 2 +- .../client_server/piclientserver_server.h | 2 +- libs/main/console/pikbdlistener.h | 2 +- libs/main/containers/pideque.h | 80 ++++++++++--------- libs/main/containers/pivector.h | 18 +++-- libs/main/containers/pivector2d.h | 28 ++++--- libs/main/core/pibase.h | 2 +- libs/main/http_server/microhttpd_server.h | 4 +- libs/main/io_devices/pibinarylog.h | 2 +- libs/main/io_devices/piiodevice.cpp | 2 +- libs/main/io_utils/pipacketextractor.h | 6 +- libs/main/io_utils/piparsehelper.h | 4 +- libs/main/math/pievaluator.h | 2 +- libs/main/math/pimathvector.h | 7 +- libs/main/state_machine/pistatemachine.h | 2 +- libs/main/state_machine/pistatemachine_base.h | 2 +- .../main/state_machine/pistatemachine_state.h | 15 ++-- .../pistatemachine_transition.cpp | 2 +- libs/main/system/pisignals.h | 2 +- libs/main/thread/piconditionvar.cpp | 12 +-- libs/main/thread/piconditionvar.h | 4 +- libs/main/thread/pithread.cpp | 30 +++---- libs/main/thread/pithreadpoolexecutor.cpp | 4 +- libs/main/thread/pithreadpoolexecutor.h | 2 +- libs/main/thread/pithreadpoolloop.cpp | 4 +- libs/main/types/pibytearray.h | 28 ++++--- libs/main/types/pivaluetree.cpp | 2 +- 28 files changed, 145 insertions(+), 131 deletions(-) diff --git a/libs/http_client/pihttpclient.cpp b/libs/http_client/pihttpclient.cpp index b6d3aa52..9dbea1e3 100644 --- a/libs/http_client/pihttpclient.cpp +++ b/libs/http_client/pihttpclient.cpp @@ -247,7 +247,7 @@ PIHTTPClient * PIHTTPClient::onFinish(std::function f) { PIHTTPClient * PIHTTPClient::onFinish(std::function f) { - on_finish = f; + on_finish = std::move(f); return this; } @@ -258,7 +258,7 @@ PIHTTPClient * PIHTTPClient::onError(std::function f) { PIHTTPClient * PIHTTPClient::onError(std::function f) { - on_error = f; + on_error = std::move(f); return this; } @@ -269,7 +269,7 @@ PIHTTPClient * PIHTTPClient::onAbort(std::function f) { PIHTTPClient * PIHTTPClient::onAbort(std::function f) { - on_abort = f; + on_abort = std::move(f); return this; } diff --git a/libs/http_server/pihttpserver.cpp b/libs/http_server/pihttpserver.cpp index b80dfd7b..796f88c4 100644 --- a/libs/http_server/pihttpserver.cpp +++ b/libs/http_server/pihttpserver.cpp @@ -45,7 +45,7 @@ bool PIHTTPServer::registerPath(const PIString & path, PIHTTP::Method method, Re Endpoint ep; if (!ep.create(path)) return false; ep.method = method; - ep.function = functor; + ep.function = std::move(functor); endpoints[ep.priority] << ep; return true; } diff --git a/libs/main/client_server/piclientserver_server.h b/libs/main/client_server/piclientserver_server.h index 14bf68bb..138d1189 100644 --- a/libs/main/client_server/piclientserver_server.h +++ b/libs/main/client_server/piclientserver_server.h @@ -103,7 +103,7 @@ public: //! \~english Sets the factory used to create accepted client objects. //! \~russian Устанавливает фабрику, создающую объекты принятых клиентов. - void setClientFactory(std::function f) { client_factory = f; } + void setClientFactory(std::function f) { client_factory = std::move(f); } private: void newClient(ServerClient * c); diff --git a/libs/main/console/pikbdlistener.h b/libs/main/console/pikbdlistener.h index b79fb85e..d74e112b 100644 --- a/libs/main/console/pikbdlistener.h +++ b/libs/main/console/pikbdlistener.h @@ -204,7 +204,7 @@ public: //! \~english Sets the callback receiving both key event and user data. //! \~russian Устанавливает обратный вызов, получающий событие клавиши и пользовательские данные. - void setSlot(KBFunc slot) { ret_func = slot; } + void setSlot(KBFunc slot) { ret_func = std::move(slot); } //! \~english Sets the callback that only receives the key event and ignores user data. //! \~russian Устанавливает обратный вызов, получающий только событие клавиши и игнорирующий пользовательские данные. diff --git a/libs/main/containers/pideque.h b/libs/main/containers/pideque.h index fe5c53be..047bf410 100644 --- a/libs/main/containers/pideque.h +++ b/libs/main/containers/pideque.h @@ -184,7 +184,7 @@ public: //! \endcode inline PIDeque(size_t piv_size, std::function f) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) - expand(piv_size, f); + expand(piv_size, std::move(f)); } //! \~english Move constructor. @@ -729,7 +729,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a indexWhere() inline const T & atWhere(std::function test, ssize_t start = 0, const T & def = T()) const { - const ssize_t i = indexWhere(test, start); + const ssize_t i = indexWhere(std::move(test), start); if (i < 0) return def; else @@ -743,7 +743,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a lastIndexWhere() inline const T & lastAtWhere(std::function test, ssize_t start = -1, const T & def = T()) const { - const ssize_t i = lastIndexWhere(test, start); + const ssize_t i = lastIndexWhere(std::move(test), start); if (i < 0) return def; else @@ -1265,7 +1265,7 @@ public: deleteT(pid_data + pid_start + new_size, pid_size - new_size); pid_size = new_size; } else if (new_size > pid_size) { - expand(new_size, f); + expand(new_size, std::move(f)); } return *this; } @@ -1328,15 +1328,15 @@ public: if (index < pid_size - 1) { const size_t os = pid_size - index - 1; memmove(reinterpret_cast(pid_data + pid_start + index + 1), - reinterpret_cast(pid_data + pid_start + index), - os * sizeof(T)); + reinterpret_cast(pid_data + pid_start + index), + os * sizeof(T)); } } else { alloc_backward(pid_size + 1, -1); if (index > 0) { memmove(reinterpret_cast(pid_data + pid_start), - reinterpret_cast(pid_data + pid_start + 1), - index * sizeof(T)); + reinterpret_cast(pid_data + pid_start + 1), + index * sizeof(T)); } } elementNew(pid_data + pid_start + index, e); @@ -1358,15 +1358,15 @@ public: if (index < pid_size - 1) { const size_t os = pid_size - index - 1; memmove(reinterpret_cast(pid_data + pid_start + index + 1), - reinterpret_cast(pid_data + pid_start + index), - os * sizeof(T)); + reinterpret_cast(pid_data + pid_start + index), + os * sizeof(T)); } } else { alloc_backward(pid_size + 1, -1); if (index > 0) { memmove(reinterpret_cast(pid_data + pid_start), - reinterpret_cast(pid_data + pid_start + 1), - index * sizeof(T)); + reinterpret_cast(pid_data + pid_start + 1), + index * sizeof(T)); } } elementNew(pid_data + pid_start + index, std::move(e)); @@ -1393,15 +1393,15 @@ public: alloc_forward(pid_size + v.pid_size); if (os > 0) { memmove(reinterpret_cast(pid_data + pid_start + index + v.pid_size), - reinterpret_cast(pid_data + pid_start + index), - os * sizeof(T)); + reinterpret_cast(pid_data + pid_start + index), + os * sizeof(T)); } } else { alloc_backward(pid_size + v.pid_size, -v.pid_size); if (index > 0) { memmove(reinterpret_cast(pid_data + pid_start), - reinterpret_cast(pid_data + pid_start + v.pid_size), - index * sizeof(T)); + reinterpret_cast(pid_data + pid_start + v.pid_size), + index * sizeof(T)); } } newT(pid_data + pid_start + index, v.pid_data + v.pid_start, v.pid_size); @@ -1426,15 +1426,15 @@ public: alloc_forward(pid_size + init_list.size()); if (os > 0) { memmove(reinterpret_cast(pid_data + pid_start + index + init_list.size()), - reinterpret_cast(pid_data + pid_start + index), + reinterpret_cast(pid_data + pid_start + index), os * sizeof(T)); } } else { alloc_backward(pid_size + init_list.size(), -init_list.size()); if (index > 0) { memmove(reinterpret_cast(pid_data + pid_start), - reinterpret_cast(pid_data + pid_start + init_list.size()), - index * sizeof(T)); + reinterpret_cast(pid_data + pid_start + init_list.size()), + index * sizeof(T)); } } newT(pid_data + pid_start + index, init_list.begin(), init_list.size()); @@ -1462,13 +1462,13 @@ public: deleteT(pid_data + pid_start + index, count); if (os <= index) { memmove(reinterpret_cast(pid_data + pid_start + index), - reinterpret_cast(pid_data + pid_start + index + count), - os * sizeof(T)); + reinterpret_cast(pid_data + pid_start + index + count), + os * sizeof(T)); } else { if (index > 0) { memmove(reinterpret_cast(pid_data + pid_start + count), - reinterpret_cast(pid_data + pid_start), - index * sizeof(T)); + reinterpret_cast(pid_data + pid_start), + index * sizeof(T)); } pid_start += count; } @@ -1540,7 +1540,7 @@ public: //! \endcode //! \~\sa \a sort() inline PIDeque & sort(std::function comp) { - std::stable_sort(begin(), end(), comp); + std::stable_sort(begin(), end(), std::move(comp)); return *this; } @@ -1654,7 +1654,13 @@ public: //! \endcode //! \~\sa \a remove(), \a removeOne(), \a removeWhere() inline PIDeque & removeWhere(std::function test) { - ssize_t j = indexWhere(test); + ssize_t j = -1; + for (size_t i = pid_start; i < pid_start + pid_size; ++i) { + if (test(pid_data[i])) { + j = ssize_t(i) - pid_start; + break; + } + } if (j != -1) { for (size_t i = j + 1; i < pid_size; ++i) { if (!test(pid_data[i + pid_start])) { @@ -2545,21 +2551,21 @@ public: if (index + count > pid_size) count = pid_size - index; ret.alloc_forward(count); memcpy(reinterpret_cast(ret.pid_data + ret.pid_start), - reinterpret_cast(pid_data + pid_start + index), - count * sizeof(T)); + reinterpret_cast(pid_data + pid_start + index), + count * sizeof(T)); const size_t os = pid_size - index - count; if (os <= index) { if (os > 0) { memmove(reinterpret_cast(pid_data + pid_start + index), - reinterpret_cast(pid_data + pid_start + index + count), - os * sizeof(T)); + reinterpret_cast(pid_data + pid_start + index + count), + os * sizeof(T)); } } else { if (index > 0) { memmove(reinterpret_cast(pid_data + pid_start + count), - reinterpret_cast(pid_data + pid_start), - index * sizeof(T)); + reinterpret_cast(pid_data + pid_start), + index * sizeof(T)); } pid_start += count; } @@ -2646,8 +2652,8 @@ private: size_t ns = (pid_rsize - pid_size) / 2; if (pid_start != ns) { memmove(reinterpret_cast(pid_data + ns), - reinterpret_cast(pid_data + pid_start), - pid_size * sizeof(T)); + reinterpret_cast(pid_data + pid_start), + pid_size * sizeof(T)); pid_start = ns; } } @@ -2656,8 +2662,8 @@ private: const size_t ns = (pid_rsize - pid_size) / 2; if (pid_start != ns) { memmove(reinterpret_cast(pid_data + ns), - reinterpret_cast(pid_data + pid_start), - pid_size * sizeof(T)); + reinterpret_cast(pid_data + pid_start), + pid_size * sizeof(T)); pid_start = ns; } } @@ -2694,8 +2700,8 @@ private: PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize)) if (pid_rsize > 0 && pid_data) { memcpy(reinterpret_cast(tmp_data + new_start), - reinterpret_cast(pid_data + pid_start), - pid_size * sizeof(T)); + reinterpret_cast(pid_data + pid_start), + pid_size * sizeof(T)); dealloc(); } pid_data = tmp_data; diff --git a/libs/main/containers/pivector.h b/libs/main/containers/pivector.h index da13d844..bdd2a700 100644 --- a/libs/main/containers/pivector.h +++ b/libs/main/containers/pivector.h @@ -184,7 +184,7 @@ public: //! \endcode inline PIVector(size_t size, std::function f) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) - expand(size, f); + expand(size, std::move(f)); } //! \~english Move constructor. @@ -725,7 +725,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a indexWhere() inline const T & atWhere(std::function test, ssize_t start = 0, const T & def = T()) const { - const ssize_t i = indexWhere(test, start); + const ssize_t i = indexWhere(std::move(test), start); if (i < 0) return def; else @@ -739,7 +739,7 @@ public: //! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! \~\sa \a lastIndexWhere() inline const T & lastAtWhere(std::function test, ssize_t start = -1, const T & def = T()) const { - const ssize_t i = lastIndexWhere(test, start); + const ssize_t i = lastIndexWhere(std::move(test), start); if (i < 0) return def; else @@ -1267,7 +1267,7 @@ public: deleteT(piv_data + new_size, piv_size - new_size); piv_size = new_size; } else if (new_size > piv_size) { - expand(new_size, f); + expand(new_size, std::move(f)); } return *this; } @@ -1486,7 +1486,7 @@ public: //! \endcode //! \~\sa \a sort() inline PIVector & sort(std::function comp) { - std::stable_sort(begin(), end(), comp); + std::stable_sort(begin(), end(), std::move(comp)); return *this; } @@ -1599,7 +1599,13 @@ public: //! \endcode //! \~\sa \a remove(), \a removeOne(), \a removeWhere() inline PIVector & removeWhere(std::function test) { - ssize_t j = indexWhere(test); + ssize_t j = -1; + for (size_t i = 0; i < piv_size; ++i) { + if (test(piv_data[i])) { + j = i; + break; + } + } if (j != -1) { for (size_t i = j + 1; i < piv_size; ++i) { if (!test(piv_data[i])) { diff --git a/libs/main/containers/pivector2d.h b/libs/main/containers/pivector2d.h index dd38c6f9..e60f5ed0 100644 --- a/libs/main/containers/pivector2d.h +++ b/libs/main/containers/pivector2d.h @@ -1070,7 +1070,7 @@ public: //! \~english Counts elements in the flat vector that pass the `test`. //! \~russian Подсчитывает элементы в плоском векторе, проходящие `test`. //! \~\sa PIVector::entries(std::function) - inline int entries(std::function test) const { return mat.entries(test); } + inline int entries(std::function test) const { return mat.entries(std::move(test)); } //! \~english Returns the first index (row, col) of `e` in the 2D array. @@ -1086,7 +1086,7 @@ public: //! \~russian Возвращает первый индекс (строка, столбец) в двумерном массиве, проходящий `test`. //! \~\sa PIVector::indexWhere() inline Index indexWhere(std::function test, ssize_t start = 0) const { - ssize_t flat = mat.indexWhere(test, start); + ssize_t flat = mat.indexWhere(std::move(test), start); if (flat < 0 || cols_ == 0) return Index{-1, -1}; return Index{flat / static_cast(cols_), flat % static_cast(cols_)}; } @@ -1104,7 +1104,7 @@ public: //! \~russian Возвращает последний индекс (строка, столбец) в двумерном массиве, проходящий `test`. //! \~\sa PIVector::lastIndexWhere() inline Index lastIndexWhere(std::function test, ssize_t start = -1) const { - ssize_t flat = mat.lastIndexWhere(test, start); + ssize_t flat = mat.lastIndexWhere(std::move(test), start); if (flat < 0 || cols_ == 0) return Index{-1, -1}; return Index{flat / static_cast(cols_), flat % static_cast(cols_)}; } @@ -1113,12 +1113,12 @@ public: //! \~english Tests if any element in the flat vector passes the `test`. //! \~russian Проверяет, проходит ли какой-либо элемент в плоском векторе `test`. //! \~\sa PIVector::any() - inline bool any(std::function test) const { return mat.any(test); } + inline bool any(std::function test) const { return mat.any(std::move(test)); } //! \~english Tests if all elements in the flat vector pass the `test`. //! \~russian Проверяет, проходят ли все элементы в плоском векторе `test`. //! \~\sa PIVector::every() - inline bool every(std::function test) const { return mat.every(test); } + inline bool every(std::function test) const { return mat.every(std::move(test)); } //! \~english Fills the entire 2D array with copies of `e`. //! \~russian Заполняет весь двумерный массив копиями `e`. @@ -1132,7 +1132,7 @@ public: //! \~russian Заполняет весь двумерный массив, используя функцию-генератор `f` на основе плоского индекса. //! \~\sa PIVector::fill(std::function) inline PIVector2D & fill(std::function f) { - mat.fill(f); + mat.fill(std::move(f)); return *this; } @@ -1228,7 +1228,7 @@ public: //! \~\sa PIVector::map() template inline PIVector2D map(std::function f) const { - return PIVector2D(rows_, cols_, mat.template map(f)); + return PIVector2D(rows_, cols_, mat.template map(std::move(f))); } //! \~english Applies a function (with row and col indices) to each element and returns a new 2D array. @@ -1250,23 +1250,26 @@ public: //! \~russian Применяет функцию к каждой строке (с возможностью изменения). //! \~\sa forEachRow() const, PIVector::forEach() inline PIVector2D & forEachRow(std::function f) { - for (size_t r = 0; r < rows_; ++r) + for (size_t r = 0; r < rows_; ++r) { f(row(r)); + } return *this; } //! \~english Applies a function to each row (read-only). //! \~russian Применяет функцию к каждой строке (только чтение). inline void forEachRow(std::function f) const { - for (size_t r = 0; r < rows_; ++r) + for (size_t r = 0; r < rows_; ++r) { f(row(r)); + } } //! \~english Applies a function to each column (modifiable). //! \~russian Применяет функцию к каждому столбцу (с возможностью изменения). inline PIVector2D & forEachColumn(std::function f) { - for (size_t c = 0; c < cols_; ++c) + for (size_t c = 0; c < cols_; ++c) { f(col(c)); + } return *this; } @@ -1274,8 +1277,9 @@ public: //! \~russian Применяет функцию к каждому столбцу (только чтение). //! \param f Function taking a \a ColConst. inline void forEachColumn(std::function f) const { - for (size_t c = 0; c < cols_; ++c) + for (size_t c = 0; c < cols_; ++c) { f(col(c)); + } } //! \~english Accumulates a value across all elements. @@ -1283,7 +1287,7 @@ public: //! \~\sa PIVector::reduce() template inline ST reduce(std::function f, const ST & initial = ST()) const { - return mat.template reduce(f, initial); + return mat.template reduce(std::move(f), initial); } //! \~english Accumulates a value across all elements with indices. diff --git a/libs/main/core/pibase.h b/libs/main/core/pibase.h index b379dea4..babe62ac 100644 --- a/libs/main/core/pibase.h +++ b/libs/main/core/pibase.h @@ -731,7 +731,7 @@ public: //! \~\brief //! \~english Constructor that takes a function to execute //! \~russian Конструктор, который принимает функцию для выполнения - explicit PIScopeExitCall(std::function f): func(f) {} + explicit PIScopeExitCall(std::function f): func(std::move(f)) {} //! \~\brief //! \~english Destructor that executes the function if it exists diff --git a/libs/main/http_server/microhttpd_server.h b/libs/main/http_server/microhttpd_server.h index e706743f..fc90b321 100644 --- a/libs/main/http_server/microhttpd_server.h +++ b/libs/main/http_server/microhttpd_server.h @@ -113,11 +113,11 @@ public: //! \~english Sets the callback that receives parsed requests and returns replies. //! \~russian Устанавливает callback, который получает разобранные запросы и возвращает ответы. - void setRequestCallback(std::function c) { callback = c; } + void setRequestCallback(std::function c) { callback = std::move(c); } //! \~english Sets the credential validator used when HTTP Basic authentication is enabled. //! \~russian Устанавливает валидатор учетных данных, используемый при включенной HTTP Basic-аутентификации. - void setBasicAuthCallback(std::function c) { callback_auth = c; } + void setBasicAuthCallback(std::function c) { callback_auth = std::move(c); } private: static void addFixedHeaders(PIHTTP::MessageMutable & msg); diff --git a/libs/main/io_devices/pibinarylog.h b/libs/main/io_devices/pibinarylog.h index f26fe5e4..38b3d21c 100644 --- a/libs/main/io_devices/pibinarylog.h +++ b/libs/main/io_devices/pibinarylog.h @@ -419,7 +419,7 @@ public: //! \~\param f //! \~english The callback function returning the next file path, or nullptr to use the internal generator. //! \~russian Функция обратного вызова, возвращающая путь к следующему файлу, или nullptr для использования внутреннего генератора. - void setFuncGetNewFilePath(std::function f) { f_new_path = f; } + void setFuncGetNewFilePath(std::function f) { f_new_path = std::move(f); } //! \~english Writes one record with explicit ID and payload. //! \~russian Записывает одну запись с явным идентификатором и данными. diff --git a/libs/main/io_devices/piiodevice.cpp b/libs/main/io_devices/piiodevice.cpp index 45344dd4..c3fb8b73 100644 --- a/libs/main/io_devices/piiodevice.cpp +++ b/libs/main/io_devices/piiodevice.cpp @@ -177,7 +177,7 @@ void PIIODevice::setReopenTimeout(PISystemTime timeout) { //! после каждого успешного потокового чтения. Метод должен быть //! в формате "bool func(void * data, uchar * readed, int size)" void PIIODevice::setThreadedReadSlot(ReadRetFunc func) { - func_read = func; + func_read = std::move(func); } diff --git a/libs/main/io_utils/pipacketextractor.h b/libs/main/io_utils/pipacketextractor.h index bb831a3a..7b41e0da 100644 --- a/libs/main/io_utils/pipacketextractor.h +++ b/libs/main/io_utils/pipacketextractor.h @@ -103,15 +103,15 @@ public: //! \~english Sets custom header validation callback. //! \~russian Устанавливает пользовательский callback проверки заголовка. - void setHeaderCheckSlot(PacketExtractorHeaderFunc f) { func_header = f; } + void setHeaderCheckSlot(PacketExtractorHeaderFunc f) { func_header = std::move(f); } //! \~english Sets custom payload validation callback. //! \~russian Устанавливает пользовательский callback проверки полезной нагрузки. - void setPayloadCheckSlot(PacketExtractorPayloadFunc f) { func_payload = f; } + void setPayloadCheckSlot(PacketExtractorPayloadFunc f) { func_payload = std::move(f); } //! \~english Sets custom footer validation callback. //! \~russian Устанавливает пользовательский callback проверки окончания пакета. - void setFooterCheckSlot(PacketExtractorFooterFunc f) { func_footer = f; } + void setFooterCheckSlot(PacketExtractorFooterFunc f) { func_footer = std::move(f); } //! \~english Switches packet extraction to mode "mode". diff --git a/libs/main/io_utils/piparsehelper.h b/libs/main/io_utils/piparsehelper.h index fe8e9433..2fb13c39 100644 --- a/libs/main/io_utils/piparsehelper.h +++ b/libs/main/io_utils/piparsehelper.h @@ -62,7 +62,7 @@ public: //! \~russian Связывает ключ "key" с callback-функцией "func" без аргументов полезной нагрузки. void assign(Key key, std::function func) { auto lf = [func](PIByteArray) { func(); }; - functions[key] << lf; + functions[key] << std::move(lf); } @@ -77,7 +77,7 @@ public: func(v); } }; - functions[key] << lf; + functions[key] << std::move(lf); } diff --git a/libs/main/math/pievaluator.h b/libs/main/math/pievaluator.h index c492cb7a..69fb9b75 100644 --- a/libs/main/math/pievaluator.h +++ b/libs/main/math/pievaluator.h @@ -175,7 +175,7 @@ struct PIP_EXPORT Function { identifier = name; arguments = args; type = bfCustom; - handler = h; + handler = std::move(h); } PIString identifier; diff --git a/libs/main/math/pimathvector.h b/libs/main/math/pimathvector.h index 2deaa403..d7974bdf 100644 --- a/libs/main/math/pimathvector.h +++ b/libs/main/math/pimathvector.h @@ -5,7 +5,7 @@ //! \~russian Математический вектор /* PIP - Platform Independent Primitives - Math vector + Math vector Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru This program is free software: you can redistribute it and/or modify @@ -805,11 +805,12 @@ public: //! \~english Applies \a f to every coordinate without modifying the vector. //! \~russian Применяет \a f к каждой координате без изменения вектора. - void forEach(std::function f) const { c.forEach(f); } + void forEach(std::function f) const { c.forEach(std::move(f)); } + //! \~english Applies \a f to every coordinate and returns this vector. //! \~russian Применяет \a f к каждой координате и возвращает этот вектор. _CVector & forEach(std::function f) { - c.forEach(f); + c.forEach(std::move(f)); return *this; } diff --git a/libs/main/state_machine/pistatemachine.h b/libs/main/state_machine/pistatemachine.h index d391bf68..a2db754e 100644 --- a/libs/main/state_machine/pistatemachine.h +++ b/libs/main/state_machine/pistatemachine.h @@ -57,7 +57,7 @@ public: //! \~english Sets a callback invoked when the machine finishes. //! \~russian Задает callback-функцию, вызываемую при завершении машины. - void setOnFinish(std::function f) { on_finish = f; } + void setOnFinish(std::function f) { on_finish = std::move(f); } //! \~english Posts an event to active states and triggers the first matching transition. diff --git a/libs/main/state_machine/pistatemachine_base.h b/libs/main/state_machine/pistatemachine_base.h index 60afe49c..661538d3 100644 --- a/libs/main/state_machine/pistatemachine_base.h +++ b/libs/main/state_machine/pistatemachine_base.h @@ -51,7 +51,7 @@ public: template FunctionBase * makeFunction(std::function func) { auto * ret = new Function(); - ret->func = func; + ret->func = std::move(func); return ret; } diff --git a/libs/main/state_machine/pistatemachine_state.h b/libs/main/state_machine/pistatemachine_state.h index 388c94ce..b79049ca 100644 --- a/libs/main/state_machine/pistatemachine_state.h +++ b/libs/main/state_machine/pistatemachine_state.h @@ -5,8 +5,8 @@ //! \~russian Объявляет состояния, используемые в PIStateMachine /* PIP - Platform Independent Primitives - State machine node - Ivan Pelipenko peri4ko@yandex.ru + State machine node + Ivan Pelipenko peri4ko@yandex.ru This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -196,10 +196,10 @@ class PIP_EXPORT PIStateLambda: public PIStateBase { public: //! \~english Creates a state backed by enter and exit callbacks. //! \~russian Создает состояние с callback-функциями входа и выхода. - PIStateLambda(std::function on_enter, std::function on_exit = nullptr, const PIString & n = {}): PIStateBase(n) { - enter = on_enter; - exit = on_exit; - } + PIStateLambda(std::function on_enter, std::function on_exit = nullptr, const PIString & n = {}) + : PIStateBase(n) + , enter(std::move(on_enter)) + , exit(std::move(on_exit)) {} //! \~english Executes the enter callback. @@ -228,9 +228,8 @@ class PIP_EXPORT PIStateFinal: public PIStateBase { public: //! \~english Creates a final state with an optional callback executed on entry. //! \~russian Создает финальное состояние с необязательной callback-функцией, выполняемой при входе. - PIStateFinal(std::function on_finish = nullptr, const PIString & n = {}): PIStateBase(n) { + PIStateFinal(std::function on_finish = nullptr, const PIString & n = {}): PIStateBase(n), enter(std::move(on_finish)) { is_final = true; - enter = on_finish; } diff --git a/libs/main/state_machine/pistatemachine_transition.cpp b/libs/main/state_machine/pistatemachine_transition.cpp index b59150b6..849681fb 100644 --- a/libs/main/state_machine/pistatemachine_transition.cpp +++ b/libs/main/state_machine/pistatemachine_transition.cpp @@ -35,7 +35,7 @@ PITransitionBase::~PITransitionBase() { PITransitionBase * PITransitionBase::addAction(std::function a) { - action = a; + action = std::move(a); return this; } diff --git a/libs/main/system/pisignals.h b/libs/main/system/pisignals.h index e308001c..55e920fb 100644 --- a/libs/main/system/pisignals.h +++ b/libs/main/system/pisignals.h @@ -68,7 +68,7 @@ public: //! \~english Installs callback that receives grabbed signals. //! \~russian Устанавливает обратный вызов, получающий перехваченные сигналы. - static void setSlot(SignalEvent slot) { ret_func = slot; } + static void setSlot(SignalEvent slot) { ret_func = std::move(slot); } //! \~english Redirects selected signals to the slot set by \a setSlot(). //! \~russian Перенаправляет выбранные сигналы в обработчик, заданный через \a setSlot(). diff --git a/libs/main/thread/piconditionvar.cpp b/libs/main/thread/piconditionvar.cpp index 0c6412c4..753b2cfc 100644 --- a/libs/main/thread/piconditionvar.cpp +++ b/libs/main/thread/piconditionvar.cpp @@ -86,11 +86,9 @@ void PIConditionVariable::wait(PIMutex & lk) { } -void PIConditionVariable::wait(PIMutex & lk, const std::function & condition) { - bool isCondition; +void PIConditionVariable::wait(PIMutex & lk, std::function condition) { while (true) { - isCondition = condition(); - if (isCondition) break; + if (condition()) break; #if defined(WINDOWS) SleepConditionVariableCS(&PRIVATE->nativeHandle, (PCRITICAL_SECTION)lk.handle(), INFINITE); #elif defined(FREERTOS) @@ -122,8 +120,7 @@ bool PIConditionVariable::waitFor(PIMutex & lk, PISystemTime timeout) { } -bool PIConditionVariable::waitFor(PIMutex & lk, PISystemTime timeout, const std::function & condition) { - bool isCondition; +bool PIConditionVariable::waitFor(PIMutex & lk, PISystemTime timeout, std::function condition) { #if defined(WINDOWS) || defined(FREERTOS) PITimeMeasurer measurer; #else @@ -135,8 +132,7 @@ bool PIConditionVariable::waitFor(PIMutex & lk, PISystemTime timeout, const std: xEventGroupClearBits(PRIVATE->nativeHandle, 1); #endif while (true) { - isCondition = condition(); - if (isCondition) break; + if (condition()) break; bool isTimeout; #if defined(WINDOWS) isTimeout = SleepConditionVariableCS(&PRIVATE->nativeHandle, diff --git a/libs/main/thread/piconditionvar.h b/libs/main/thread/piconditionvar.h index 4487edea..25626a09 100644 --- a/libs/main/thread/piconditionvar.h +++ b/libs/main/thread/piconditionvar.h @@ -106,7 +106,7 @@ public: //! \param condition вызываемый объект или функция, не принимающая аргументов и возвращающая значение, которое может быть оценено как //! bool. Вызывается повторно, пока не примет значение true //! - virtual void wait(PIMutex & lk, const std::function & condition); + virtual void wait(PIMutex & lk, std::function condition); //! \~english Waits for at most \a timeout and returns \c true if awakened before it expires. @@ -167,7 +167,7 @@ public: //! bool. Вызывается повторно, пока не примет значение true //! \return false если достигнут таймаут, или true если условие пробуждения истинно //! - virtual bool waitFor(PIMutex & lk, PISystemTime timeout, const std::function & condition); + virtual bool waitFor(PIMutex & lk, PISystemTime timeout, std::function condition); private: PRIVATE_DECLARATION(PIP_EXPORT) diff --git a/libs/main/thread/pithread.cpp b/libs/main/thread/pithread.cpp index 4e03b73a..0f9aa389 100644 --- a/libs/main/thread/pithread.cpp +++ b/libs/main/thread/pithread.cpp @@ -540,7 +540,7 @@ PRIVATE_DEFINITION_END(PIThread) PIThread::PIThread(void * data, ThreadFunc func, bool startNow, PISystemTime loop_delay): PIObject() { PIINTROSPECTION_THREAD_NEW(this); data_ = data; - ret_func = func; + ret_func = std::move(func); terminating = running_ = lockRun = false; priority_ = piNormal; delay_ = loop_delay; @@ -609,13 +609,13 @@ bool PIThread::start(PISystemTime loop_delay) { bool PIThread::start(ThreadFunc func) { - ret_func = func; + ret_func = std::move(func); return start(); } bool PIThread::start(ThreadFunc func, PISystemTime loop_delay) { - ret_func = func; + ret_func = std::move(func); delay_ = loop_delay; return start(); } @@ -641,7 +641,7 @@ bool PIThread::startOnce() { bool PIThread::startOnce(ThreadFunc func) { - ret_func = func; + ret_func = std::move(func); return startOnce(); } @@ -738,12 +738,12 @@ bool PIThread::_startThread(void * func) { #ifdef FREERTOS auto name_ba = createThreadName(); - if (xTaskCreate((__THREAD_FUNC_RET__ (*)(void *))func, - (const char *)name_ba.data(), // A name just for humans - 128, // This stack size can be checked & adjusted by reading the Stack Highwater - this, - priority_, - &PRIVATE->thread) == pdPASS) { + if (xTaskCreate((__THREAD_FUNC_RET__(*)(void *))func, + (const char *)name_ba.data(), // A name just for humans + 128, // This stack size can be checked & adjusted by reading the Stack Highwater + this, + priority_, + &PRIVATE->thread) == pdPASS) { tid_ = (llong)PRIVATE->thread; return true; } @@ -752,7 +752,7 @@ bool PIThread::_startThread(void * func) { if (PRIVATE->thread) CloseHandle(PRIVATE->thread); # ifdef CC_GCC - PRIVATE->thread = (void *)_beginthreadex(0, 0, (__THREAD_FUNC_RET__ (*)(void *))func, this, CREATE_SUSPENDED, 0); + PRIVATE->thread = (void *)_beginthreadex(0, 0, (__THREAD_FUNC_RET__(*)(void *))func, this, CREATE_SUSPENDED, 0); # else PRIVATE->thread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)func, this, CREATE_SUSPENDED, 0); # endif @@ -766,7 +766,7 @@ bool PIThread::_startThread(void * func) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - int ret = pthread_create(&PRIVATE->thread, &attr, (__THREAD_FUNC_RET__ (*)(void *))func, this); + int ret = pthread_create(&PRIVATE->thread, &attr, (__THREAD_FUNC_RET__(*)(void *))func, this); pthread_attr_destroy(&attr); // PICout(PICoutManipulators::DefaultControls) << "pthread_create" << PRIVATE->thread; // piCout << "started" << PRIVATE->thread; @@ -884,8 +884,8 @@ void PIThread::_runThread() { PIINTROSPECTION_THREAD_RUN(this); // PICout(PICoutManipulators::DefaultControls) << "thread" << this << "lock" << "..."; if (lockRun) thread_mutex.lock(); - // PICout(PICoutManipulators::DefaultControls) << "thread" << this << "lock" << "ok"; - // PICout(PICoutManipulators::DefaultControls) << "thread" << this << "run" << "..."; + // PICout(PICoutManipulators::DefaultControls) << "thread" << this << "lock" << "ok"; + // PICout(PICoutManipulators::DefaultControls) << "thread" << this << "run" << "..."; #ifdef PIP_INTROSPECTION PITimeMeasurer _tm; #endif @@ -1042,7 +1042,7 @@ void PIThread::runOnce(PIObject * object, const char * handler, const PIString & void PIThread::runOnce(std::function func, const PIString & name) { PIThread * t = new PIThread(); t->setName(name); - t->setSlot(func); + t->setSlot(std::move(func)); #ifndef MICRO_PIP __PIThreadCollection::instance()->startedAuto(t); CONNECT0(void, t, stopped, __PIThreadCollection::instance(), stoppedAuto); diff --git a/libs/main/thread/pithreadpoolexecutor.cpp b/libs/main/thread/pithreadpoolexecutor.cpp index 55d3ae29..1973b6bd 100644 --- a/libs/main/thread/pithreadpoolexecutor.cpp +++ b/libs/main/thread/pithreadpoolexecutor.cpp @@ -68,8 +68,8 @@ PIThreadPoolExecutor::~PIThreadPoolExecutor() { } -void PIThreadPoolExecutor::execute(const std::function & runnable) { - if (!isShutdown_) taskQueue.offer(runnable); +void PIThreadPoolExecutor::execute(std::function runnable) { + if (!isShutdown_) taskQueue.offer(std::move(runnable)); } diff --git a/libs/main/thread/pithreadpoolexecutor.h b/libs/main/thread/pithreadpoolexecutor.h index a94cd4e5..c302dbd2 100644 --- a/libs/main/thread/pithreadpoolexecutor.h +++ b/libs/main/thread/pithreadpoolexecutor.h @@ -59,7 +59,7 @@ public: //! \~russian //! Это вызов по принципу best-effort без ожидания результата и без сообщения о том, была ли задача принята. //! \После запроса на завершение новые задачи игнорируются. - void execute(const std::function & runnable); + void execute(std::function runnable); //! \~english Requests immediate shutdown and stops worker threads without waiting for queued tasks to finish. //! \~russian Запрашивает немедленное завершение и останавливает рабочие потоки без ожидания завершения задач в очереди. diff --git a/libs/main/thread/pithreadpoolloop.cpp b/libs/main/thread/pithreadpoolloop.cpp index b8e1494f..41367adc 100644 --- a/libs/main/thread/pithreadpoolloop.cpp +++ b/libs/main/thread/pithreadpoolloop.cpp @@ -136,7 +136,7 @@ PIThreadPoolLoop::~PIThreadPoolLoop() { void PIThreadPoolLoop::setFunction(std::function f) { - func = f; + func = std::move(f); } @@ -163,6 +163,6 @@ void PIThreadPoolLoop::exec(int index_start, int index_count) { void PIThreadPoolLoop::exec(int index_start, int index_count, std::function f) { - setFunction(f); + setFunction(std::move(f)); exec(index_start, index_count); } diff --git a/libs/main/types/pibytearray.h b/libs/main/types/pibytearray.h index c519b152..14fd688f 100644 --- a/libs/main/types/pibytearray.h +++ b/libs/main/types/pibytearray.h @@ -198,7 +198,7 @@ public: //! Метод возвращает **false** при любом условии для пустого массива. //! \~\details //! \~\sa \a every(), \a contains(), \a entries(), \a forEach() - inline bool any(std::function test) const { return d.any(test); } + inline bool any(std::function test) const { return d.any(std::move(test)); } //! \~english Tests whether all elements in the array passes the test //! implemented by the provided function `test`. @@ -213,7 +213,7 @@ public: //! Метод возвращает **true** при любом условии для пустого массива. //! \~\details //! \~\sa \a any(), \a contains(), \a entries(), \a forEach() - inline bool every(std::function test) const { return d.every(test); } + inline bool every(std::function test) const { return d.every(std::move(test)); } //! \~english Full access to element by `index`. //! \~russian Полный доступ к элементу по индексу `index`. @@ -340,7 +340,7 @@ public: //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 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); } + inline int entries(std::function test, ssize_t start = 0) const { return d.entries(std::move(test), start); } bool startsWith(const PIByteArray & o) const; @@ -405,7 +405,9 @@ public: //! piCout << v.indexWhere([](const uchar & s){return s > 10;}); // -1 //! \endcode //! \~\sa \a indexOf(), \a lastIndexOf(), \a lastIndexWhere(), \a contains() - inline ssize_t indexWhere(std::function test, ssize_t start = 0) const { return d.indexWhere(test, start); } + inline ssize_t indexWhere(std::function test, ssize_t start = 0) const { + return d.indexWhere(std::move(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. @@ -469,7 +471,7 @@ public: //! и означает, что просматривается весь массив. //! \~\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); + return d.lastIndexWhere(std::move(test), start); } //! \~english Pointer to array @@ -525,7 +527,7 @@ public: //! \~\details //! \~\sa \a resize() inline PIByteArray & fill(std::function f) { - d.fill(f); + d.fill(std::move(f)); return *this; } @@ -570,7 +572,7 @@ public: //! лишние элементы удаляются с конца массива. //! \~\sa \a size(), \a clear() inline PIByteArray & resize(size_t new_size, std::function f) { - d.resize(new_size, f); + d.resize(new_size, std::move(f)); return *this; } @@ -738,7 +740,7 @@ public: //! \~\details //! \~\sa \a remove(), \a removeOne(), \a removeWhere() inline PIByteArray & removeWhere(std::function test) { - d.removeWhere(test); + d.removeWhere(std::move(test)); return *this; } @@ -950,7 +952,7 @@ public: //! 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)); } + inline PIByteArray filter(std::function test) const { return PIByteArray(d.filter(std::move(test))); } //! \~english Execute function `void f(const uchar & e)` for every element in array. //! \~russian Выполняет функцию `void f(const uchar & e)` для каждого элемента массива. @@ -966,7 +968,7 @@ public: //! 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); } + inline void forEach(std::function f) const { d.forEach(std::move(f)); } //! \~english Execute function `void f(uchar & e)` for every element in array. //! \~russian Выполняет функцию `void f(uchar & e)` для каждого элемента массива. @@ -982,7 +984,7 @@ public: //! \endcode //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() inline PIByteArray & forEach(std::function f) { - d.forEach(f); + d.forEach(std::move(f)); return *this; } @@ -1005,7 +1007,7 @@ public: //! \~\sa \a forEach(), \a reduce() template inline PIDeque map(std::function f) const { - return d.map(f); + return d.map(std::move(f)); } //! \~english Applies the function `ST f(const uchar & e, const ST & acc)` @@ -1051,7 +1053,7 @@ public: //! \~\sa \a forEach(), \a map() template inline ST reduce(std::function f, const ST & initial = ST()) const { - return d.reduce(f, initial); + return d.reduce(std::move(f), initial); } //! \~english Convert data to Base 64 and return this byte array diff --git a/libs/main/types/pivaluetree.cpp b/libs/main/types/pivaluetree.cpp index b21f6279..a02ce13c 100644 --- a/libs/main/types/pivaluetree.cpp +++ b/libs/main/types/pivaluetree.cpp @@ -262,7 +262,7 @@ PIValueTree & PIValueTree::remove(const PIString & name) { void PIValueTree::forEachRecursive(std::function func) { - forEachRecursiveInternal(func); + forEachRecursiveInternal(std::move(func)); }