From 6660a45c4121b29a1cf6193dd50fdfa7671e93fa Mon Sep 17 00:00:00 2001
From: Michael Friedrich <michael.friedrich@icinga.com>
Date: Wed, 9 May 2018 16:55:14 +0200
Subject: [PATCH] Implement Array::Unique() and add unit tests

refs #4732
---
 lib/base/array-script.cpp | 10 +---------
 lib/base/array.cpp        | 13 +++++++++++++
 lib/base/array.hpp        |  1 +
 test/CMakeLists.txt       |  1 +
 test/base-array.cpp       | 21 +++++++++++++++++++++
 5 files changed, 37 insertions(+), 9 deletions(-)

diff --git a/lib/base/array-script.cpp b/lib/base/array-script.cpp
index 3f83dd934..c12585b1f 100644
--- a/lib/base/array-script.cpp
+++ b/lib/base/array-script.cpp
@@ -251,15 +251,7 @@ static Array::Ptr ArrayUnique()
 	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
 	Array::Ptr self = static_cast<Array::Ptr>(vframe->Self);
 	REQUIRE_NOT_NULL(self);
-
-	std::set<Value> result;
-
-	ObjectLock olock(self);
-	for (const Value& item : self) {
-		result.insert(item);
-	}
-
-	return Array::FromSet(result);
+	return self->Unique();
 }
 
 static void ArrayFreeze()
diff --git a/lib/base/array.cpp b/lib/base/array.cpp
index ac2ade93e..30cf7eba3 100644
--- a/lib/base/array.cpp
+++ b/lib/base/array.cpp
@@ -305,6 +305,19 @@ String Array::ToString() const
 	return msgbuf.str();
 }
 
+Array::Ptr Array::Unique() const
+{
+	std::set<Value> result;
+
+	ObjectLock olock(this);
+
+	for (const Value& item : m_Data) {
+		result.insert(item);
+	}
+
+	return Array::FromSet(result);
+}
+
 void Array::Freeze()
 {
 	ObjectLock olock(this);
diff --git a/lib/base/array.hpp b/lib/base/array.hpp
index 768cee131..62bcf7e2e 100644
--- a/lib/base/array.hpp
+++ b/lib/base/array.hpp
@@ -112,6 +112,7 @@ public:
 
 	String ToString() const override;
 
+	Array::Ptr Unique() const;
 	void Freeze();
 
 	Value GetFieldByName(const String& field, bool sandboxed, const DebugInfo& debugInfo) const override;
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 5fce79833..29a16646f 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -63,6 +63,7 @@ add_boost_test(base
     base_array/resize
     base_array/insert
     base_array/remove
+    base_array/unique
     base_array/foreach
     base_array/clone
     base_array/json
diff --git a/test/base-array.cpp b/test/base-array.cpp
index 86be0f510..74bbd692c 100644
--- a/test/base-array.cpp
+++ b/test/base-array.cpp
@@ -102,6 +102,27 @@ BOOST_AUTO_TEST_CASE(remove)
 	BOOST_CHECK(array->GetLength() == 0);
 }
 
+BOOST_AUTO_TEST_CASE(unique)
+{
+	Array::Ptr array = new Array();
+	array->Add("group1");
+	array->Add("group2");
+	array->Add("group1");
+	array->Add("group2");
+
+	Array::Ptr result;
+
+	{
+		ObjectLock olock(array);
+		result = array->Unique();
+	}
+
+	BOOST_CHECK(result->GetLength() == 2);
+	result->Sort();
+
+	BOOST_CHECK(result->Get(0) == "group1");
+	BOOST_CHECK(result->Get(1) == "group2");
+}
 BOOST_AUTO_TEST_CASE(foreach)
 {
 	Array::Ptr array = new Array();
-- 
2.40.0