Remove some dynamic memory allocations

This commit is contained in:
Bartosz Wieczorek 2025-05-30 11:21:27 +02:00
parent cd65d742a5
commit 8edd768488
7 changed files with 46 additions and 33 deletions

View File

@ -128,7 +128,7 @@ FetchContent_Declare(
RapidJSON RapidJSON
URL https://github.com/Tencent/rapidjson/archive/refs/tags/v1.1.0.zip URL https://github.com/Tencent/rapidjson/archive/refs/tags/v1.1.0.zip
URL_HASH MD5=ceb1cf16e693a3170c173dc040a9d2bd URL_HASH MD5=ceb1cf16e693a3170c173dc040a9d2bd
PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_LIST_DIR}/patches/rapidjson.patch # PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_LIST_DIR}/patches/rapidjson.patch
) )
if(NOT RapidJSON_POPULATED) if(NOT RapidJSON_POPULATED)

View File

@ -35,7 +35,7 @@ class AuthenticationStep {
auto event = eventListener.listen(); auto event = eventListener.listen();
if(event.status == transactionConfirmed ){ if(event.status == transactionConfirmed ){
log(LogLevel::Debug, " Transaction confirmed"); log(LogLevel::Debug, " Transaction confirmed");
return AuthenticationStatus{AuthenticationStatus::Action::Confirmed, std::string{event.accessToken.value().c_str()}}; return AuthenticationStatus{AuthenticationStatus::Action::Confirmed, event.accessToken.value().c_str()};
} }
log(LogLevel::Debug, " Transaction denied"); log(LogLevel::Debug, " Transaction denied");
return AuthenticationStatus{AuthenticationStatus::Action::Denied}; return AuthenticationStatus{AuthenticationStatus::Action::Denied};

View File

@ -73,7 +73,7 @@ class CoreHandler : public CoreHandlerInterface< CoreHandler< HttpHandler > > {
public: public:
CoreHandler() = delete; CoreHandler() = delete;
CoreHandler(const Configuration & config) : _config{config}, _ws{std::make_unique<WebSocket>(_config.apiServer)}, http{_config} { CoreHandler(const Configuration & config) : _config{config}, _ws{std::make_unique<WebSocket>(_config)}, http{_config} {
log(LogLevel::Debug, "Core Handler apiServer: %s", _config.apiServer.c_str()); log(LogLevel::Debug, "Core Handler apiServer: %s", _config.apiServer.c_str());
} }
CoreHandler(CoreHandler &&) noexcept = default; CoreHandler(CoreHandler &&) noexcept = default;
@ -132,7 +132,7 @@ class CoreHandler : public CoreHandlerInterface< CoreHandler< HttpHandler > > {
tl::unexpected< Error > handleCoreException(std::string_view exceptionString) const { tl::unexpected< Error > handleCoreException(std::string_view exceptionString) const {
log(LogLevel::Debug, "TMP got core exception: %s", exceptionString.data() ); log(LogLevel::Debug, "TMP got core exception: %s", exceptionString.data() );
// can happen only dyring check application step // can happen only during check application step
if(auto error = RublonCheckApplicationException::fromString(exceptionString); error.has_value()) if(auto error = RublonCheckApplicationException::fromString(exceptionString); error.has_value())
return tl::unexpected{Error{error.value()}}; return tl::unexpected{Error{error.value()}};
@ -184,7 +184,7 @@ class CoreHandler : public CoreHandlerInterface< CoreHandler< HttpHandler > > {
bool createWSConnection(std::string_view tid) const { bool createWSConnection(std::string_view tid) const {
if(not _ws){ if(not _ws){
_ws.reset(new WebSocket (_config.apiServer)); _ws.reset(new WebSocket (_config));
} }
/// TODO connect can be separated from subscribtion on event /// TODO connect can be separated from subscribtion on event
/// TODO status of attach is not checked /// TODO status of attach is not checked

View File

@ -13,8 +13,6 @@
#include <sys/utsname.h> #include <sys/utsname.h>
[[deprecated]] extern std::string g_tid;
namespace rublon { namespace rublon {
template < class MethodSelect_t = MethodSelect > template < class MethodSelect_t = MethodSelect >

View File

@ -1,15 +1,18 @@
#pragma once #pragma once
#include "rublon/static_string.hpp"
#include <optional>
#include <rublon/stdlib.hpp> #include <rublon/stdlib.hpp>
namespace rublon { namespace rublon {
class AuthenticationStatus { class AuthenticationStatus {
public: public:
using tokenT = std::optional< StaticString< 64 > >;
enum class Action { Denied, Confirmed, Bypass }; enum class Action { Denied, Confirmed, Bypass };
AuthenticationStatus(Action action, std::string authenticationToken = "") AuthenticationStatus(Action action, const char * token = nullptr)
: _action{action}, _authenticationToken{std::move(authenticationToken)} {} : _action{action}, _authenticationToken{token == nullptr ? tokenT{std::nullopt} : tokenT{token}} {}
constexpr bool userAuthorized() const { constexpr bool userAuthorized() const {
return _action == Action::Confirmed; return _action == Action::Confirmed;
@ -20,12 +23,12 @@ class AuthenticationStatus {
} }
std::string_view accessToken() const { std::string_view accessToken() const {
return _authenticationToken; return {_authenticationToken->c_str(), _authenticationToken->size()};
} }
private: private:
Action _action; Action _action;
std::string _authenticationToken; /// TODO dynamic mem tokenT _authenticationToken; /// TODO dynamic mem
}; };
} // namespace rublon } // namespace rublon

View File

@ -31,19 +31,22 @@ template < size_t N >
class StaticString : public details::StaticStringBase { class StaticString : public details::StaticStringBase {
public: public:
constexpr StaticString() = default; constexpr StaticString() = default;
constexpr StaticString(const char (&chars)[N]) : m_str(toStdArray(chars)) {} constexpr StaticString(const char (&chars)[N]) : m_str(toStdArray(chars)), _size{N} {}
constexpr StaticString(std::array< const char, N > chars) : m_str(std::move(chars)) {} constexpr StaticString(std::array< const char, N > chars) : m_str(std::move(chars)), _size{N} {}
constexpr StaticString(const char * str) { constexpr StaticString(const char * str) {
std::strncpy(m_str.data(), str, N); _size = std::min(strlen(str), N);
std::memcpy(m_str.data(), str, _size);
} }
void operator=(const char * str) { void operator=(const char * str) {
std::strncpy(m_str.data(), str, N); _size = std::min(strlen(str), N);
std::memcpy(m_str.data(), str, _size);
} }
void operator=(std::string_view str) { void operator=(std::string_view str) {
std::strncpy(m_str.data(), str.data(), N); _size = std::min(str.size(), N);
std::memcpy(m_str.data(), str.data(), _size);
} }
const char * c_str() const noexcept { const char * c_str() const noexcept {
@ -67,16 +70,23 @@ class StaticString : public details::StaticStringBase {
} }
std::size_t size() const { std::size_t size() const {
return strlen(m_str.data()); return _size;
} }
constexpr std::size_t capacity() const noexcept { constexpr std::size_t capacity() const noexcept {
return N - 1; return N - 1;
} }
template < std::size_t M > StaticString< N > & operator+=(const char * rhs) {
constexpr StaticString< N + M - 1 > operator+(const StaticString< M > & rhs) const { auto remaining = capacity() - _size;
return join(resize< N - 1 >(m_str), rhs.m_str); auto rhs_len = std::strlen(rhs);
auto copy_len = std::min(rhs_len, remaining);
std::strncpy(data() + _size, rhs, copy_len);
_size += copy_len;
data()[_size] = '\0'; // null
return *this;
} }
template < std::size_t M > template < std::size_t M >
@ -88,6 +98,7 @@ class StaticString : public details::StaticStringBase {
private: private:
std::array< char, N + 1 > m_str{}; std::array< char, N + 1 > m_str{};
std::size_t _size;
}; };
template < size_t N > template < size_t N >

View File

@ -130,19 +130,21 @@ class WebSocket {
} }
bool attachToTransactionConfirmationChannel(std::string_view transaction_id) { bool attachToTransactionConfirmationChannel(std::string_view transaction_id) {
/// TODO change to StaticString and += StaticString< 128 > subscribe_message{};
std::array< char, 128 > subscribe_message{0}; unsigned char buf[128 + LWS_PRE] = {};
std::array< char, 128 > buf{0};
sprintf(subscribe_message.data(), R"msg(42["subscribe",{"channel":"transactionConfirmation.%s"}])msg", transaction_id.data()); subscribe_message += R"msg(42["subscribe",{"channel":"transactionConfirmation.)msg";
memcpy(&buf[LWS_PRE], subscribe_message.data(), strlen(subscribe_message.data())); subscribe_message += transaction_id.data();
subscribe_message += "}]";
log(LogLevel::Debug, "WS send message: %s", subscribe_message.data()); memcpy(buf + LWS_PRE, subscribe_message.data(), subscribe_message.size());
int bytes_sent = lws_write(wsi, ( unsigned char * ) &buf[LWS_PRE], strlen(subscribe_message.data()), LWS_WRITE_TEXT);
log(LogLevel::Debug, "WS send message: %s", subscribe_message.c_str());
int bytes_sent = lws_write(wsi, buf + LWS_PRE, subscribe_message.size(), LWS_WRITE_TEXT);
log(LogLevel::Debug, "WS send: %d bytes", bytes_sent); log(LogLevel::Debug, "WS send: %d bytes", bytes_sent);
if(bytes_sent < ( int ) strlen(subscribe_message.data())) { if(bytes_sent < ( int ) subscribe_message.size()) {
log(LogLevel::Error, "Failed to send subscribe message"); log(LogLevel::Error, "Failed to send subscribe message");
return false; return false;
} }
@ -151,7 +153,6 @@ class WebSocket {
bool AttachToCore(std::string_view tid) { bool AttachToCore(std::string_view tid) {
log(LogLevel::Debug, "connecting to %s", ccinfo.address); log(LogLevel::Debug, "connecting to %s", ccinfo.address);
/// needed here only for rublon core api URL, so 1k fine
lws_client_connect_via_info(&ccinfo); lws_client_connect_via_info(&ccinfo);
const int seconds = 10; const int seconds = 10;
@ -209,7 +210,7 @@ class WebSocket {
case LWS_CALLBACK_CLIENT_WRITEABLE: { case LWS_CALLBACK_CLIENT_WRITEABLE: {
// Perform the Socket.IO 4.x handshake (send `40` message) // Perform the Socket.IO 4.x handshake (send `40` message)
const std::string_view handshake = "40"; const std::string_view handshake = "40";
unsigned char buf[64]; unsigned char buf[64]={};
memcpy(&buf[LWS_PRE], handshake.data(), handshake.size()); memcpy(&buf[LWS_PRE], handshake.data(), handshake.size());
lws_write(wsi, &buf[LWS_PRE], handshake.size(), LWS_WRITE_TEXT); lws_write(wsi, &buf[LWS_PRE], handshake.size(), LWS_WRITE_TEXT);
log(LogLevel::Debug, "Sent Socket.IO handshake"); log(LogLevel::Debug, "Sent Socket.IO handshake");