blob: 118f24e6c646d0b6b783bf4f4c14f2141e5ffd6a [file] [log] [blame]
Zane Shelley200c3452019-09-26 11:46:30 -05001#include <util/hei_flyweight.hpp>
2
3#include "gtest/gtest.h"
4
5using namespace libhei;
6
7class Foo
8{
9 public:
10 Foo() = default;
Zane Shelley83da2452019-10-25 15:45:34 -050011 explicit Foo(int i) : iv_i(i) {}
Zane Shelley200c3452019-09-26 11:46:30 -050012 int get() const { return iv_i; }
Zane Shelley83da2452019-10-25 15:45:34 -050013 bool operator==(const Foo & i_r) const { return iv_i == i_r.iv_i; }
14 bool operator<(const Foo & i_r) const { return iv_i < i_r.iv_i; }
Zane Shelley200c3452019-09-26 11:46:30 -050015 private:
16 int iv_i = 0;
17};
18
Zane Shelley83da2452019-10-25 15:45:34 -050019Foo & addFoo(int i)
Zane Shelley200c3452019-09-26 11:46:30 -050020{
Zane Shelley83da2452019-10-25 15:45:34 -050021 return Flyweight<Foo>::getSingleton().get(Foo { i });
Zane Shelley200c3452019-09-26 11:46:30 -050022}
23
Zane Shelley83da2452019-10-25 15:45:34 -050024TEST(FlyweightTest, TestSet1)
Zane Shelley200c3452019-09-26 11:46:30 -050025{
26 // Add some unique entries in a random order and keep track of where those
27 // enties exist in memory.
28 Foo * a[5];
29 a[1] = &(addFoo(1));
30 a[2] = &(addFoo(2));
31 a[0] = &(addFoo(0));
32 a[4] = &(addFoo(4));
33 a[3] = &(addFoo(3));
34
35 // Now add more entries and verify the 'new' entries match the same
36 // addresses as the previously added entries.
Zane Shelley83da2452019-10-25 15:45:34 -050037 for (int i = 4; i >= 0; i--)
Zane Shelley200c3452019-09-26 11:46:30 -050038 {
Zane Shelley83da2452019-10-25 15:45:34 -050039 ASSERT_EQ(a[i], &(addFoo(i)));
Zane Shelley200c3452019-09-26 11:46:30 -050040 }
41
42 // At this point, we have proven that duplicate entries will return
43 // references to the original unique entries. There is probably more we can
44 // do here, but this is enough to prove the Flyweight class follows the
45 // flyweight design pattern.
46}