From d6dc6b1b0c6dd5cb293f2dd77482c549add9737b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=95=88=EC=A0=95=EA=B7=A0?= Date: Thu, 1 Aug 2024 14:29:37 +0900 Subject: [PATCH] Improving the performance of toJSONString in CRDTTree --- Sources/Document/CRDT/CRDTTree.swift | 40 +++++++++++----------------- Sources/Document/CRDT/RHT.swift | 7 +++++ 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/Sources/Document/CRDT/CRDTTree.swift b/Sources/Document/CRDT/CRDTTree.swift index 03005e4f..3a7f8584 100644 --- a/Sources/Document/CRDT/CRDTTree.swift +++ b/Sources/Document/CRDT/CRDTTree.swift @@ -487,34 +487,26 @@ final class CRDTTreeNode: IndexTreeNode { } var toJSONString: String { - if self.type == DefaultTreeNodeType.text.rawValue { - return "{\"type\":\(self.type.toJSONString),\"value\":\((self.value as String).toJSONString)}" - } else { - var childrenString = "" - if children.isEmpty == false { - childrenString = children.compactMap { $0.toJSONString }.joined(separator: ",") - } - - var resultString = "{\"type\":\(self.type.toJSONString),\"children\":[\(childrenString)]" - - if let attributes = self.attrs?.toObject().mapValues({ $0.value }), attributes.isEmpty == false { - let sortedKeys = attributes.keys.sorted() - - let attrsString = sortedKeys.compactMap { key in - if let value = attributes[key] { - return "\(key.toJSONString):\(value)" - } else { - return nil - } - }.joined(separator: ",") + if let data = try? JSONSerialization.data(withJSONObject: toDictionary, options: [.sortedKeys]), + let result = String(data: data, encoding: .utf8) + { + return result + } - resultString += ",\"attributes\":{\(attrsString)}" - } + return "{}" + } - resultString += "}" + var toDictionary: [String: Any] { + var dictionary: [String: Any] = ["type": self.type] - return resultString + if self.type == DefaultTreeNodeType.text.rawValue { + dictionary["value"] = self.value as String + } else { + dictionary["children"] = self.children.map { $0.toDictionary } + dictionary["attributes"] = self.attrs?.toDictionary } + + return dictionary } /** diff --git a/Sources/Document/CRDT/RHT.swift b/Sources/Document/CRDT/RHT.swift index 946d22fa..bca0e028 100644 --- a/Sources/Document/CRDT/RHT.swift +++ b/Sources/Document/CRDT/RHT.swift @@ -230,6 +230,13 @@ class RHT { return result } + var toDictionary: [String: Any] { + self.nodeMapByKey.compactMapValues { node -> Any? in + guard !node.isRemoved else { return nil } + return try? JSONSerialization.jsonObject(with: Data(node.value.utf8), options: .fragmentsAllowed) + } + } + /** * `purge` purges the given child node. */