memory_c: add comparison operators with strings constants

This commit is contained in:
Moritz Bunkus 2017-07-21 17:16:06 +02:00
parent 7fb3003919
commit 3b2ff9b6ae
2 changed files with 66 additions and 10 deletions

View File

@ -187,16 +187,6 @@ public:
return its_counter ? its_counter->ptr : nullptr;
}
bool operator ==(memory_c const &cmp) const {
return (get_size() == cmp.get_size())
&& ((get_buffer() && cmp.get_buffer()) || (!get_buffer() && !cmp.get_buffer()))
&& (get_buffer() ? !::memcmp(get_buffer(), cmp.get_buffer(), get_size()) : true);
}
bool operator !=(memory_c const &cmp) const {
return !(*this == cmp);
}
std::string to_string() const {
if (!is_allocated() || !get_size())
return {};
@ -263,6 +253,39 @@ private:
}
};
inline bool
operator ==(memory_c const &a,
memory_c const &b) {
return (a.get_size() == b.get_size())
&& ((a.get_buffer() && b.get_buffer()) || (!a.get_buffer() && !b.get_buffer()))
&& (a.get_buffer() ? !std::memcmp(a.get_buffer(), b.get_buffer(), a.get_size()) : true);
}
inline bool
operator !=(memory_c const &a,
memory_c const &b) {
return !(a == b);
}
inline bool
operator ==(memory_c const &a,
char const *b) {
if (!a.get_buffer() && !b)
return true;
if (!a.get_buffer() || !b)
return false;
return (a.get_size() == std::strlen(b))
&& !std::memcmp(a.get_buffer(), b, a.get_size());
}
inline bool
operator !=(memory_c const &a,
char const *b) {
return !(a == b);
}
class memory_slice_cursor_c {
protected:
size_t m_pos, m_pos_in_slice, m_size;

View File

@ -0,0 +1,33 @@
#include "common/common_pch.h"
#include "common/memory.h"
#include "gtest/gtest.h"
namespace {
TEST(Memory, OperatorEq) {
auto m1 = memory_c::clone("hello");
auto m2 = memory_c::alloc(5);
auto m3 = memory_c::clone("world");
std::memcpy(m2->get_buffer(), "hello", 5);
EXPECT_TRUE(*m1 == *m2);
EXPECT_TRUE(*m1 == "hello");
EXPECT_FALSE(*m1 == *m3);
EXPECT_FALSE(*m1 == "world");
}
TEST(Memory, OperatorNotEq) {
auto m1 = memory_c::clone("hello");
auto m2 = memory_c::alloc(5);
auto m3 = memory_c::clone("world");
std::memcpy(m2->get_buffer(), "hello", 5);
EXPECT_FALSE(*m1 != *m2);
EXPECT_FALSE(*m1 != "hello");
EXPECT_TRUE(*m1 != *m3);
EXPECT_TRUE(*m1 != "world");
}
}