From c8bed6445b244a5d9021dbd9a2ff19d80c03917b Mon Sep 17 00:00:00 2001 From: Noel Grandin Date: Mon, 15 Jun 2020 20:32:25 +0200 Subject: new json writer for LOK we shave about 3 memory copies off in the process, and make the class play nicely with our string types. Change-Id: I1f614fb35b1de499ac99e3b33ac638ad81054bed Reviewed-on: https://gerrit.libreoffice.org/c/core/+/96393 Tested-by: Noel Grandin Reviewed-by: Noel Grandin --- include/tools/json_writer.hxx | 86 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 include/tools/json_writer.hxx (limited to 'include/tools') diff --git a/include/tools/json_writer.hxx b/include/tools/json_writer.hxx new file mode 100644 index 000000000000..e811bb90e277 --- /dev/null +++ b/include/tools/json_writer.hxx @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +#pragma once + +#include +#include +#include + +/** Simple JSON encoder designed specifically for LibreOfficeKit purposes. + * + * (1) Minimal allocations/re-allocations/copying + * (2) Small/simple JSON documents + * (3) ascii property names + */ +namespace tools +{ +class ScopedJsonWriterNode; + +class TOOLS_DLLPUBLIC JsonWriter +{ + friend class ScopedJsonWriterNode; + + int mSpaceAllocated; + std::unique_ptr maBuffer; + int mStartNodeCount; + char* mPos; + bool mbFirstFieldInNode; + +public: + JsonWriter(); + ~JsonWriter(); + + [[nodiscard]] ScopedJsonWriterNode startNode(const char*); + + void put(const char* pPropName, const OUString& rPropValue); + void put(const char* pPropName, const OString& rPropValue); + void put(const char* pPropName, const char* pPropVal); + void put(const char*, int); + + /** Hands ownership of the the underlying storage buffer to the caller, + * after this no more document modifications may be written. */ + char* extractData(); + +private: + void endNode(); + void addCommaBeforeField(); + + inline void ensureSpace(int noMoreBytesRequired) + { + int currentUsed = mPos - maBuffer.get(); + if (currentUsed + noMoreBytesRequired >= mSpaceAllocated) + { + auto newSize = std::max(mSpaceAllocated * 2, (currentUsed + noMoreBytesRequired) * 2); + auto pNew = new char[newSize]; + memcpy(pNew, maBuffer.get(), currentUsed); + maBuffer.reset(pNew); + mPos = maBuffer.get(); + } + } +}; + +/** + * Auto-closes the node. + */ +class ScopedJsonWriterNode +{ + friend class JsonWriter; + + JsonWriter& mrWriter; + + ScopedJsonWriterNode(JsonWriter& rWriter) + : mrWriter(rWriter) + { + } + +public: + ~ScopedJsonWriterNode() { mrWriter.endNode(); } +}; +}; +/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */ -- cgit