blob: 472358dab7179b73f585ab7d3d0de8d33bd273dd [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 Shelley7f7a42d2019-10-28 13:28:31 -050012
13 int get() const
14 {
15 return iv_i;
16 }
17
18 bool operator==(const Foo& i_r) const
19 {
20 return iv_i == i_r.iv_i;
21 }
22
23 bool operator<(const Foo& i_r) const
24 {
25 return iv_i < i_r.iv_i;
26 }
27
Zane Shelley200c3452019-09-26 11:46:30 -050028 private:
29 int iv_i = 0;
30};
31
Zane Shelleyfe27b652019-10-28 11:33:07 -050032Foo& addFoo(int i)
Zane Shelley200c3452019-09-26 11:46:30 -050033{
Zane Shelley83da2452019-10-25 15:45:34 -050034 return Flyweight<Foo>::getSingleton().get(Foo { i });
Zane Shelley200c3452019-09-26 11:46:30 -050035}
36
Zane Shelley83da2452019-10-25 15:45:34 -050037TEST(FlyweightTest, TestSet1)
Zane Shelley200c3452019-09-26 11:46:30 -050038{
39 // Add some unique entries in a random order and keep track of where those
40 // enties exist in memory.
Zane Shelleyfe27b652019-10-28 11:33:07 -050041 Foo* a[5];
Zane Shelley200c3452019-09-26 11:46:30 -050042 a[1] = &(addFoo(1));
43 a[2] = &(addFoo(2));
44 a[0] = &(addFoo(0));
45 a[4] = &(addFoo(4));
46 a[3] = &(addFoo(3));
47
48 // Now add more entries and verify the 'new' entries match the same
49 // addresses as the previously added entries.
Zane Shelley83da2452019-10-25 15:45:34 -050050 for (int i = 4; i >= 0; i--)
Zane Shelley200c3452019-09-26 11:46:30 -050051 {
Zane Shelley83da2452019-10-25 15:45:34 -050052 ASSERT_EQ(a[i], &(addFoo(i)));
Zane Shelley200c3452019-09-26 11:46:30 -050053 }
54
55 // At this point, we have proven that duplicate entries will return
56 // references to the original unique entries. There is probably more we can
57 // do here, but this is enough to prove the Flyweight class follows the
58 // flyweight design pattern.
59}