From 3b2ff9b6ae70926786f21912d38f5959c6318e6b Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Fri, 21 Jul 2017 17:16:06 +0200 Subject: [PATCH] memory_c: add comparison operators with strings constants --- src/common/memory.h | 43 +++++++++++++++++++++++++++--------- tests/unit/common/memory.cpp | 33 +++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 tests/unit/common/memory.cpp diff --git a/src/common/memory.h b/src/common/memory.h index 1220cdc58..9914caeaa 100644 --- a/src/common/memory.h +++ b/src/common/memory.h @@ -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; diff --git a/tests/unit/common/memory.cpp b/tests/unit/common/memory.cpp new file mode 100644 index 000000000..171be9daa --- /dev/null +++ b/tests/unit/common/memory.cpp @@ -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"); +} + +}