Fix handling non null-terminated string_views in LookupByKey (#8203)

* Reproduce the error in a unit test

Reproduces #8200

* Overload KeyCompareWithValue to work for string-like objects

This fixes #8200.

* Extra tests

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
This commit is contained in:
mpawlowski-eyeo
2024-03-25 18:39:51 +01:00
committed by GitHub
parent 67eb95de92
commit 0cfb7eb80b
9 changed files with 117 additions and 0 deletions

View File

@@ -2417,8 +2417,20 @@ class CppGenerator : public BaseGenerator {
// Generate KeyCompareWithValue function
if (is_string) {
// Compares key against a null-terminated char array.
code_ += " int KeyCompareWithValue(const char *_{{FIELD_NAME}}) const {";
code_ += " return strcmp({{FIELD_NAME}}()->c_str(), _{{FIELD_NAME}});";
code_ += " }";
// Compares key against any string-like object (e.g. std::string_view or
// std::string) that implements operator< comparison with const char*.
code_ += " template<typename StringType>";
code_ +=
" int KeyCompareWithValue(const StringType& _{{FIELD_NAME}}) const "
"{";
code_ +=
" if ({{FIELD_NAME}}()->c_str() < _{{FIELD_NAME}}) return -1;";
code_ += " if (_{{FIELD_NAME}} < {{FIELD_NAME}}()->c_str()) return 1;";
code_ += " return 0;";
} else if (is_array) {
const auto &elem_type = field.value.type.VectorType();
std::string input_type = "::flatbuffers::Array<" +