diff --git a/components/core/src/clp/ffi/utils.cpp b/components/core/src/clp/ffi/utils.cpp index 3f77564d2..c85c47701 100644 --- a/components/core/src/clp/ffi/utils.cpp +++ b/components/core/src/clp/ffi/utils.cpp @@ -16,10 +16,17 @@ using std::string_view; namespace clp::ffi { auto validate_and_escape_utf8_string(string_view raw) -> std::optional { - string_view::const_iterator next_char_to_copy_it{raw.cbegin()}; std::optional ret_val; auto& escaped{ret_val.emplace()}; escaped.reserve(raw.size() + (raw.size() / 2)); + if (false == validate_and_append_escaped_utf8_string(raw, escaped)) { + return std::nullopt; + } + return ret_val; +} + +auto validate_and_append_escaped_utf8_string(std::string_view src, std::string& dst) -> bool { + string_view::const_iterator next_char_to_copy_it{src.cbegin()}; auto escape_handler = [&](string_view::const_iterator it) -> void { // Allocate 6 + 1 size buffer to format control characters as "\u00bb", with the last byte @@ -63,20 +70,20 @@ auto validate_and_escape_utf8_string(string_view raw) -> std::optional { } } if (escape_required) { - escaped.append(next_char_to_copy_it, it); - escaped += escaped_char; + dst.append(next_char_to_copy_it, it); + dst += escaped_char; next_char_to_copy_it = it + 1; } }; - if (false == validate_utf8_string(raw, escape_handler)) { - return std::nullopt; + if (false == validate_utf8_string(src, escape_handler)) { + return false; } - if (raw.cend() != next_char_to_copy_it) { - escaped.append(next_char_to_copy_it, raw.cend()); + if (src.cend() != next_char_to_copy_it) { + dst.append(next_char_to_copy_it, src.cend()); } - return ret_val; + return true; } } // namespace clp::ffi diff --git a/components/core/src/clp/ffi/utils.hpp b/components/core/src/clp/ffi/utils.hpp index 160ed687b..8a90169a1 100644 --- a/components/core/src/clp/ffi/utils.hpp +++ b/components/core/src/clp/ffi/utils.hpp @@ -15,6 +15,16 @@ namespace clp::ffi { */ [[nodiscard]] auto validate_and_escape_utf8_string(std::string_view raw ) -> std::optional; + +/** + * Validates whether the given string is UTF-8 encoded, and append the src to the dst by escaping + * any characters to make the string compatible with the JSON specification. + * @param src The source string to validate and escape. + * @param dst Outputs the destination string with escaped src appended. + * @return Whether the src is a valid UTF-8 encoded string. + */ +[[nodiscard]] auto +validate_and_append_escaped_utf8_string(std::string_view src, std::string& dst) -> bool; } // namespace clp::ffi #endif // CLP_FFI_UTILS_HPP