SmallString: Fix new buffer size not getting set

This commit is contained in:
Stenzek 2023-09-23 22:08:46 +10:00
parent 610a40490a
commit 5c099d55da
1 changed files with 13 additions and 8 deletions

View File

@ -57,56 +57,61 @@ SmallStringBase::~SmallStringBase()
void SmallStringBase::reserve(u32 new_reserve) void SmallStringBase::reserve(u32 new_reserve)
{ {
if (m_buffer_size >= new_reserve) const u32 real_reserve = new_reserve + 1;
if (m_buffer_size >= real_reserve)
return; return;
if (m_on_heap) if (m_on_heap)
{ {
char* new_ptr = static_cast<char*>(std::realloc(m_buffer, new_reserve)); char* new_ptr = static_cast<char*>(std::realloc(m_buffer, real_reserve));
if (!new_ptr) if (!new_ptr)
Panic("Memory allocation failed."); Panic("Memory allocation failed.");
#ifdef _DEBUG #ifdef _DEBUG
std::memset(new_ptr + m_length, 0, new_reserve - m_length); std::memset(new_ptr + m_length, 0, real_reserve - m_length);
#endif #endif
m_buffer = new_ptr; m_buffer = new_ptr;
} }
else else
{ {
char* new_ptr = static_cast<char*>(std::malloc(new_reserve)); char* new_ptr = static_cast<char*>(std::malloc(real_reserve));
if (!new_ptr) if (!new_ptr)
Panic("Memory allocation failed."); Panic("Memory allocation failed.");
if (m_length > 0) if (m_length > 0)
std::memcpy(new_ptr, m_buffer, m_length); std::memcpy(new_ptr, m_buffer, m_length);
#ifdef _DEBUG #ifdef _DEBUG
std::memset(new_ptr + m_length, 0, new_reserve - m_length); std::memset(new_ptr + m_length, 0, real_reserve - m_length);
#else #else
new_ptr[m_length] = 0; new_ptr[m_length] = 0;
#endif #endif
m_buffer = new_ptr; m_buffer = new_ptr;
m_on_heap = true; m_on_heap = true;
} }
m_buffer_size = new_reserve;
} }
void SmallStringBase::shrink_to_fit() void SmallStringBase::shrink_to_fit()
{ {
if (!m_on_heap || m_length == m_buffer_size) const u32 buffer_size = (m_length + 1);
if (!m_on_heap || buffer_size == m_buffer_size)
return; return;
if (m_length == 0) if (m_length == 0)
{ {
std::free(m_buffer); std::free(m_buffer);
m_buffer = nullptr;
m_buffer_size = 0; m_buffer_size = 0;
return; return;
} }
char* new_ptr = static_cast<char*>(std::realloc(m_buffer, m_length)); char* new_ptr = static_cast<char*>(std::realloc(m_buffer, buffer_size));
if (!new_ptr) if (!new_ptr)
Panic("Memory allocation failed."); Panic("Memory allocation failed.");
m_buffer = new_ptr; m_buffer = new_ptr;
m_buffer_size = m_length; m_buffer_size = buffer_size;
} }
std::string_view SmallStringBase::view() const std::string_view SmallStringBase::view() const