From 820b908b80a8c1e4280fba14c4ff679972a121d3 Mon Sep 17 00:00:00 2001 From: Daniel Hammer Date: Fri, 19 Jun 2026 18:37:19 +0200 Subject: [PATCH] fix: convention fix, performance improvement in kcp::cstringstream --- kernel/src/Api/BuildNo.hpp | 2 +- kernel/src/CppLib/Stream.cpp | 36 ++++++++++++++++++++++++------------ kernel/src/CppLib/Stream.hpp | 1 + 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/kernel/src/Api/BuildNo.hpp b/kernel/src/Api/BuildNo.hpp index 848f27d..28e56c6 100644 --- a/kernel/src/Api/BuildNo.hpp +++ b/kernel/src/Api/BuildNo.hpp @@ -12,4 +12,4 @@ #pragma once -#define MONTAUK_BUILD_NUMBER 127 +#define MONTAUK_BUILD_NUMBER 128 diff --git a/kernel/src/CppLib/Stream.cpp b/kernel/src/CppLib/Stream.cpp index 59f0688..64987ab 100644 --- a/kernel/src/CppLib/Stream.cpp +++ b/kernel/src/CppLib/Stream.cpp @@ -13,28 +13,40 @@ kcp::cstringstream::cstringstream() { this->string = nullptr; this->size = 0; + this->capacity = 0; } kcp::cstringstream::~cstringstream() { - delete this->string; + // string is allocated via g_heap->Realloc, so it must be released through + // the heap allocator, not operator delete. + if (this->string != nullptr) { + Memory::g_heap->Free(this->string); + } } kcp::cstringstream& kcp::cstringstream::operator<<(char c) { - this->string = (char *)Memory::g_heap->Realloc((void *)this->string, this->size + 2); + // Grow geometrically (capacity doubles) so appending N chars is amortized + // O(N) instead of a Realloc on every single character. + if (this->capacity < this->size + 2) { + std::size_t newCapacity = (this->capacity == 0) ? 16 : (this->capacity * 2); + if (newCapacity < this->size + 2) { + newCapacity = this->size + 2; + } - if (this->string == nullptr) - { - Kt::KernelLogStream(Kt::ERROR, "kcp::cstringstream") << "Character streaming failed due to failed allocation."; - return *this; + char* grown = (char *)Memory::g_heap->Realloc((void *)this->string, newCapacity); + if (grown == nullptr) + { + Kt::KernelLogStream(Kt::ERROR, "kcp::cstringstream") << "Character streaming failed due to failed allocation."; + return *this; + } + + this->string = grown; + this->capacity = newCapacity; } - - char* ref = (char *)&string[size]; - *ref = c; - - ref++; - *ref = '\0'; + this->string[this->size] = c; + this->string[this->size + 1] = '\0'; this->size++; return *this; diff --git a/kernel/src/CppLib/Stream.hpp b/kernel/src/CppLib/Stream.hpp index f26c821..4b1d619 100644 --- a/kernel/src/CppLib/Stream.hpp +++ b/kernel/src/CppLib/Stream.hpp @@ -22,6 +22,7 @@ namespace kcp { class cstringstream { char* string; std::size_t size; + std::size_t capacity; base current_base = base::dec;