mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-03 04:21:13 +00:00
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:
@@ -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<" +
|
||||
|
||||
Reference in New Issue
Block a user