avoid a memcpy when constructing output of tools::JsonWriter

we can store the data in an rtl::OString object and then return
that directly

Change-Id: I65af6820bfd3135b38d437cf9736fffff8924e88
Reviewed-on: https://gerrit.libreoffice.org/c/core/+/164291
Tested-by: Jenkins
Reviewed-by: Noel Grandin <noel.grandin@collabora.co.uk>
This commit is contained in:
Noel Grandin 2024-03-02 16:47:10 +02:00 committed by Noel Grandin
parent f4fc510a28
commit 06daf1719e
2 changed files with 15 additions and 12 deletions

View file

@ -33,7 +33,7 @@ class TOOLS_DLLPUBLIC JsonWriter
~ScopedJsonWriterNode() { mrWriter.endNode(closing); }
};
char* mpBuffer;
rtl_String* mpBuffer;
char* mPos;
int mSpaceAllocated;
int mStartNodeCount;
@ -96,14 +96,14 @@ private:
inline void addValidationMark()
{
#ifndef NDEBUG
*(mpBuffer + mSpaceAllocated - 1) = JSON_WRITER_DEBUG_MARKER;
*(mpBuffer->buffer + mSpaceAllocated - 1) = JSON_WRITER_DEBUG_MARKER;
#endif
}
inline void validate()
{
#ifndef NDEBUG
unsigned char c = *(mpBuffer + mSpaceAllocated - 1);
unsigned char c = *(mpBuffer->buffer + mSpaceAllocated - 1);
assert(c == JSON_WRITER_DEBUG_MARKER);
#endif
}

View file

@ -20,8 +20,8 @@ namespace tools
constexpr int DEFAULT_BUFFER_SIZE = 2048;
JsonWriter::JsonWriter()
: mpBuffer(static_cast<char*>(malloc(DEFAULT_BUFFER_SIZE)))
, mPos(mpBuffer)
: mpBuffer(rtl_string_alloc(DEFAULT_BUFFER_SIZE))
, mPos(mpBuffer->buffer)
, mSpaceAllocated(DEFAULT_BUFFER_SIZE)
, mStartNodeCount(0)
, mbFirstFieldInNode(true)
@ -38,7 +38,7 @@ JsonWriter::JsonWriter()
JsonWriter::~JsonWriter()
{
assert(mbClosed && "forgot to extract data?");
free(mpBuffer);
rtl_string_release(mpBuffer);
}
JsonWriter::ScopedJsonWriterNode<'}'> JsonWriter::startNode(std::string_view pNodeName)
@ -291,12 +291,15 @@ void JsonWriter::addCommaBeforeField()
void JsonWriter::ensureSpace(int noMoreBytesRequired)
{
assert(!mbClosed && "already extracted data");
int currentUsed = mPos - mpBuffer;
int currentUsed = mPos - mpBuffer->buffer;
if (currentUsed + noMoreBytesRequired >= mSpaceAllocated)
{
auto newSize = (currentUsed + noMoreBytesRequired) * 2;
mpBuffer = static_cast<char*>(realloc(mpBuffer, newSize));
mPos = mpBuffer + currentUsed;
rtl_String* pNewBuffer = rtl_string_alloc(newSize);
memcpy(pNewBuffer->buffer, mpBuffer->buffer, currentUsed);
rtl_string_release(mpBuffer);
mpBuffer = pNewBuffer;
mPos = mpBuffer->buffer + currentUsed;
mSpaceAllocated = newSize;
addValidationMark();
@ -339,13 +342,13 @@ OString JsonWriter::finishAndGetAsOString()
*mPos = 0;
mbClosed = true;
OString ret(mpBuffer, mPos - mpBuffer);
return ret;
mpBuffer->length = mPos - mpBuffer->buffer;
return mpBuffer;
}
bool JsonWriter::isDataEquals(std::string_view s) const
{
return std::string_view(mpBuffer, static_cast<size_t>(mPos - mpBuffer)) == s;
return std::string_view(mpBuffer->buffer, static_cast<size_t>(mPos - mpBuffer->buffer)) == s;
}
} // namespace tools