Support nulls in String compare, CreateSharedString (#5060)

This commit is contained in:
Matt Frantz
2018-12-03 09:48:50 -08:00
committed by Wouter van Oortmerssen
parent 79cd55bd3a
commit 2aa0d9a54d
2 changed files with 64 additions and 3 deletions

View File

@@ -344,6 +344,14 @@ template<typename T> static inline size_t VectorLength(const Vector<T> *v) {
return v ? v->Length() : 0;
}
// Lexicographically compare two strings (possibly containing nulls), and
// return true if the first is less than the second.
static inline bool StringLessThan(const char *a_data, uoffset_t a_size,
const char *b_data, uoffset_t b_size) {
const auto cmp = memcmp(a_data, b_data, (std::min)(a_size, b_size));
return cmp == 0 ? a_size < b_size : cmp < 0;
}
struct String : public Vector<char> {
const char *c_str() const { return reinterpret_cast<const char *>(Data()); }
std::string str() const { return std::string(c_str(), Length()); }
@@ -357,7 +365,7 @@ struct String : public Vector<char> {
// clang-format on
bool operator<(const String &o) const {
return strcmp(c_str(), o.c_str()) < 0;
return StringLessThan(this->data(), this->size(), o.data(), o.size());
}
};
@@ -1834,8 +1842,8 @@ protected:
bool operator()(const Offset<String> &a, const Offset<String> &b) const {
auto stra = reinterpret_cast<const String *>(buf_->data_at(a.o));
auto strb = reinterpret_cast<const String *>(buf_->data_at(b.o));
return strncmp(stra->c_str(), strb->c_str(),
(std::min)(stra->size(), strb->size()) + 1) < 0;
return StringLessThan(stra->data(), stra->size(),
strb->data(), strb->size());
}
const vector_downward *buf_;
};