Reduce packetstream allocation frequency.

git-svn-id: https://www.unprompted.com/svn/projects/tildefriends/trunk@3825 ed5197a5-7fde-0310-b194-c3ffbd925b24
This commit is contained in:
Cory McWilliams 2022-02-06 00:46:34 +00:00
parent e59eb66c1d
commit 8f35004a01

View File

@ -12,6 +12,7 @@ typedef struct _tf_packetstream_t {
uv_pipe_t stream; uv_pipe_t stream;
char* buffer; char* buffer;
size_t buffer_size; size_t buffer_size;
size_t buffer_capacity;
bool destroyed; bool destroyed;
} tf_packetstream_t; } tf_packetstream_t;
@ -27,6 +28,11 @@ void tf_packetstream_destroy(tf_packetstream_t* stream)
stream->onreceive = NULL; stream->onreceive = NULL;
stream->onreceive_user_data = NULL; stream->onreceive_user_data = NULL;
stream->destroyed = true; stream->destroyed = true;
if (stream->buffer)
{
free(stream->buffer);
stream->buffer = NULL;
}
if (stream->stream.data) if (stream->stream.data)
{ {
tf_packetstream_close(stream); tf_packetstream_close(stream);
@ -61,7 +67,6 @@ static void _packetstream_process_messages(tf_packetstream_t* stream)
size_t consumed = sizeof(length) + sizeof(packet_type) + length; size_t consumed = sizeof(length) + sizeof(packet_type) + length;
memmove(stream->buffer, stream->buffer + consumed, stream->buffer_size - consumed); memmove(stream->buffer, stream->buffer + consumed, stream->buffer_size - consumed);
stream->buffer_size -= consumed; stream->buffer_size -= consumed;
stream->buffer = realloc(stream->buffer, stream->buffer_size);
} }
else else
{ {
@ -77,11 +82,23 @@ static void _packetstream_on_read(uv_stream_t* handle, ssize_t count, const uv_b
{ {
if (count > 0) if (count > 0)
{ {
char* new_buffer = realloc(stream->buffer, stream->buffer_size + count); char* write_buffer = stream->buffer;
if (new_buffer) if (stream->buffer_size + count > stream->buffer_capacity)
{ {
memcpy(new_buffer + stream->buffer_size, buffer->base, count); if (!stream->buffer_capacity)
stream->buffer = new_buffer; {
stream->buffer_capacity = 256;
}
while (stream->buffer_capacity < stream->buffer_size + count)
{
stream->buffer_capacity *= 2;
}
write_buffer = realloc(write_buffer, stream->buffer_capacity);
}
if (write_buffer)
{
memcpy(write_buffer + stream->buffer_size, buffer->base, count);
stream->buffer = write_buffer;
stream->buffer_size += count; stream->buffer_size += count;
} }
_packetstream_process_messages(stream); _packetstream_process_messages(stream);
@ -133,6 +150,11 @@ static void _tf_packetstream_handle_closed(uv_handle_t* handle)
{ {
tf_packetstream_t* packetstream = handle->data; tf_packetstream_t* packetstream = handle->data;
handle->data = NULL; handle->data = NULL;
if (packetstream->buffer)
{
free(packetstream->buffer);
packetstream->buffer = NULL;
}
if (packetstream->destroyed) if (packetstream->destroyed)
{ {
free(packetstream); free(packetstream);