Vector: Use memcmp for comparing two vectors with trivial elements

This commit is contained in:
Andreas Kling 2019-08-07 15:05:10 +02:00
parent 6d97caf124
commit e8e85f5457
Notes: sideshowbarker 2024-07-19 12:50:41 +09:00
3 changed files with 39 additions and 8 deletions

View file

@ -142,4 +142,29 @@ TEST_CASE(prepend_vector_object)
EXPECT_EQ(objects[5].subobject->value, 3);
}
TEST_CASE(vector_compare)
{
Vector<int> ints;
Vector<int> same_ints;
for (int i = 0; i < 1000; ++i) {
ints.append(i);
same_ints.append(i);
}
EXPECT_EQ(ints.size(), 1000);
EXPECT_EQ(ints, same_ints);
Vector<String> strings;
Vector<String> same_strings;
for (int i = 0; i < 1000; ++i) {
strings.append(String::number(i));
same_strings.append(String::number(i));
}
EXPECT_EQ(strings.size(), 1000);
EXPECT_EQ(strings, same_strings);
}
TEST_MAIN(Vector)

View file

@ -7,12 +7,12 @@ namespace AK {
template<typename T>
struct GenericTraits {
static constexpr bool is_trivial() { return false; }
static bool equals(const T& a, const T& b) { return a == b; }
};
template<typename T>
struct Traits : public GenericTraits<T> {
static constexpr bool is_trivial() { return false; }
};
template<>

View file

@ -85,6 +85,18 @@ public:
for (size_t i = 0; i < count; ++i)
new (&destination[i]) T(source[i]);
}
static bool compare(const T* a, const T* b, size_t count)
{
if constexpr (Traits<T>::is_trivial())
return !memcmp(a, b, count * sizeof(T));
for (size_t i = 0; i < count; ++i) {
if (a[i] != b[i])
return false;
}
return true;
}
};
template<typename T, int inline_capacity = 0>
@ -178,13 +190,7 @@ public:
{
if (m_size != other.m_size)
return false;
for (int i = 0; i < m_size; ++i) {
if (at(i) != other.at(i))
return false;
}
return true;
return TypedTransfer<T>::compare(data(), other.data(), size());
}
bool operator!=(const Vector& other) const