Skip to content

Commit

Permalink
Added TBTempBuffer::AppendSpace and tuned reserve size.
Browse files Browse the repository at this point in the history
  • Loading branch information
fruxo committed Jul 4, 2014
1 parent 6690a48 commit 5ae7178
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/tb/tb_tempbuffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,30 @@ bool TBTempBuffer::Reserve(int size)
return true;
}

int TBTempBuffer::GetAppendReserveSize(int needed_size) const
{
// Reserve some extra memory to reduce the reserve calls.
needed_size *= 2;
return needed_size < 32 ? 32 : needed_size;
}

bool TBTempBuffer::Append(const char *data, int size)
{
int needed_size = m_append_pos + size;
if (needed_size > m_data_size)
{
// Reserve some extra memory to reduce the reserve calls.
needed_size = needed_size + size + 32;
if (!Reserve(needed_size))
return false;
}
if (m_append_pos + size > m_data_size && !Reserve(GetAppendReserveSize(m_append_pos + size)))
return false;
memcpy(m_data + m_append_pos, data, size);
m_append_pos += size;
return true;
}

bool TBTempBuffer::AppendSpace(int size)
{
if (m_append_pos + size > m_data_size && !Reserve(GetAppendReserveSize(m_append_pos + size)))
return false;
m_append_pos += size;
return true;
}

bool TBTempBuffer::AppendString(const char *str)
{
// Add 1 to include the null termination in the data.
Expand Down
7 changes: 7 additions & 0 deletions src/tb/tb_tempbuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ class TBTempBuffer
Returns false on OOM. */
bool Append(const char *data, int size);

/** Increase the append position with size bytes without
writing any data. This is useful if you want to write
the data later and want to make sure space is reserved.
Returns false on OOM. */
bool AppendSpace(int size);

/** Append a null terminated string (including the null termination)
at the end of the buffer. The append position will be increased
with the length of the text (excluding the null termination) so
Expand All @@ -55,6 +61,7 @@ class TBTempBuffer
/** Return the current append position in in bytes. */
int GetAppendPos() const { return m_append_pos; }
private:
int GetAppendReserveSize(int needed_size) const;
char *m_data;
int m_data_size;
int m_append_pos;
Expand Down

0 comments on commit 5ae7178

Please sign in to comment.