From 75e067e3df11f0d6b782ecc791bce3cadce25c6b Mon Sep 17 00:00:00 2001 From: Niels Lohmann Date: Thu, 22 Oct 2026 22:45:19 +0200 Subject: [PATCH] Return early from json_pointer::to_string() for an empty pointer Signed-off-by: Niels Lohmann --- include/nlohmann/detail/json_pointer.hpp | 16 +++++++++------- single_include/nlohmann/json.hpp | 16 +++++++++------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/include/nlohmann/detail/json_pointer.hpp b/include/nlohmann/detail/json_pointer.hpp index 8e9a74fb3..1988840b5 100644 --- a/include/nlohmann/detail/json_pointer.hpp +++ b/include/nlohmann/detail/json_pointer.hpp @@ -80,6 +80,11 @@ class json_pointer /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ string_t to_string() const { + if (reference_tokens.empty()) + { + return string_t(); + } + // one buffer: every token adds its escaped form (at least its length) and a slash std::size_t length = 0; bool plain = true; @@ -98,14 +103,11 @@ class json_pointer { // nothing to escape: the tokens are copied into the string result.resize(length); - if (length != 0) + char* out = &result[0]; + for (const auto& reference_token : reference_tokens) { - char* out = &result[0]; - for (const auto& reference_token : reference_tokens) - { - *out++ = '/'; - out = std::copy(reference_token.data(), reference_token.data() + reference_token.size(), out); - } + *out++ = '/'; + out = std::copy(reference_token.data(), reference_token.data() + reference_token.size(), out); } return result; } diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index cd5f87737..a56969fb7 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -22430,6 +22430,11 @@ class json_pointer /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ string_t to_string() const { + if (reference_tokens.empty()) + { + return string_t(); + } + // one buffer: every token adds its escaped form (at least its length) and a slash std::size_t length = 0; bool plain = true; @@ -22448,14 +22453,11 @@ class json_pointer { // nothing to escape: the tokens are copied into the string result.resize(length); - if (length != 0) + char* out = &result[0]; + for (const auto& reference_token : reference_tokens) { - char* out = &result[0]; - for (const auto& reference_token : reference_tokens) - { - *out++ = '/'; - out = std::copy(reference_token.data(), reference_token.data() + reference_token.size(), out); - } + *out++ = '/'; + out = std::copy(reference_token.data(), reference_token.data() + reference_token.size(), out); } return result; }