Skip to content

Commit

Permalink
Add append option
Browse files Browse the repository at this point in the history
  • Loading branch information
LinZhihao-723 committed Jun 26, 2024
1 parent ebc1c4f commit 690379c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
23 changes: 15 additions & 8 deletions components/core/src/clp/ffi/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,17 @@ using std::string_view;

namespace clp::ffi {
auto validate_and_escape_utf8_string(string_view raw) -> std::optional<string> {
string_view::const_iterator next_char_to_copy_it{raw.cbegin()};
std::optional<std::string> 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
Expand Down Expand Up @@ -63,20 +70,20 @@ auto validate_and_escape_utf8_string(string_view raw) -> std::optional<string> {
}
}
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
10 changes: 10 additions & 0 deletions components/core/src/clp/ffi/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ namespace clp::ffi {
*/
[[nodiscard]] auto validate_and_escape_utf8_string(std::string_view raw
) -> std::optional<std::string>;

/**
* 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

0 comments on commit 690379c

Please sign in to comment.