From 7ab21c6afdaf4011b990a3a30c326b788d7d530d Mon Sep 17 00:00:00 2001 From: SChernykh Date: Wed, 23 Feb 2022 17:07:50 +0100 Subject: [PATCH] TCPServer: reduced memory usage --- src/common.h | 2 ++ src/p2p_server.cpp | 2 +- src/tcp_server.h | 2 +- src/tcp_server.inl | 12 ++++++++---- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/common.h b/src/common.h index d35ede1..2f37724 100644 --- a/src/common.h +++ b/src/common.h @@ -113,6 +113,8 @@ FORCEINLINE uint64_t udiv128(uint64_t hi, uint64_t lo, uint64_t divisor, uint64_ } #endif +template FORCEINLINE T round_up(T a, size_t granularity) { return static_cast(((a + (granularity - static_cast(1))) / granularity) * granularity); } + struct hash { alignas(8) uint8_t h[HASH_SIZE]; diff --git a/src/p2p_server.cpp b/src/p2p_server.cpp index 40d3287..8cecb0b 100644 --- a/src/p2p_server.cpp +++ b/src/p2p_server.cpp @@ -801,7 +801,7 @@ void P2PServer::on_broadcast() } return p - p0; - }); + }); } } } diff --git a/src/tcp_server.h b/src/tcp_server.h index e14c899..7b9db55 100644 --- a/src/tcp_server.h +++ b/src/tcp_server.h @@ -98,7 +98,7 @@ public: { Client* m_client; uv_write_t m_write; - char m_data[WRITE_BUF_SIZE]; + std::vector m_data; }; uv_mutex_t m_writeBuffersLock; diff --git a/src/tcp_server.inl b/src/tcp_server.inl index 4381f1f..6c40335 100644 --- a/src/tcp_server.inl +++ b/src/tcp_server.inl @@ -548,10 +548,12 @@ bool TCPServer::send_internal(Client* client, Sen buf = new WriteBuf(); } - const size_t bytes_written = callback(buf->m_data); + // callback_buf is used in only 1 thread, so it's safe + static uint8_t callback_buf[WRITE_BUF_SIZE]; + const size_t bytes_written = callback(callback_buf); - if (bytes_written > sizeof(buf->m_data)) { - LOGERR(0, "send callback wrote " << bytes_written << " bytes, expected no more than " << sizeof(buf->m_data) << " bytes"); + if (bytes_written > WRITE_BUF_SIZE) { + LOGERR(0, "send callback wrote " << bytes_written << " bytes, expected no more than " << WRITE_BUF_SIZE << " bytes"); panic(); } @@ -566,9 +568,11 @@ bool TCPServer::send_internal(Client* client, Sen buf->m_client = client; buf->m_write.data = buf; + buf->m_data.reserve(round_up(bytes_written, 64)); + buf->m_data.assign(callback_buf, callback_buf + bytes_written); uv_buf_t bufs[1]; - bufs[0].base = buf->m_data; + bufs[0].base = reinterpret_cast(buf->m_data.data()); bufs[0].len = static_cast(bytes_written); const int err = uv_write(&buf->m_write, reinterpret_cast(&client->m_socket), bufs, 1, Client::on_write);