Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 1 | #include <util/hei_flyweight.hpp> |
| 2 | |
| 3 | #include "gtest/gtest.h" |
| 4 | |
| 5 | using namespace libhei; |
| 6 | |
| 7 | class Foo |
| 8 | { |
| 9 | public: |
| 10 | Foo() = default; |
Zane Shelley | 83da245 | 2019-10-25 15:45:34 -0500 | [diff] [blame] | 11 | explicit Foo(int i) : iv_i(i) {} |
Zane Shelley | 7f7a42d | 2019-10-28 13:28:31 -0500 | [diff] [blame] | 12 | |
| 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 | { |
Zane Shelley | c477199 | 2019-10-28 22:01:49 -0500 | [diff] [blame] | 25 | return iv_i < i_r.iv_i; |
Zane Shelley | 7f7a42d | 2019-10-28 13:28:31 -0500 | [diff] [blame] | 26 | } |
| 27 | |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 28 | private: |
| 29 | int iv_i = 0; |
| 30 | }; |
| 31 | |
Zane Shelley | fe27b65 | 2019-10-28 11:33:07 -0500 | [diff] [blame] | 32 | Foo& addFoo(int i) |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 33 | { |
Zane Shelley | c477199 | 2019-10-28 22:01:49 -0500 | [diff] [blame] | 34 | return Flyweight<Foo>::getSingleton().get(Foo{i}); |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 35 | } |
| 36 | |
Zane Shelley | 83da245 | 2019-10-25 15:45:34 -0500 | [diff] [blame] | 37 | TEST(FlyweightTest, TestSet1) |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 38 | { |
| 39 | // Add some unique entries in a random order and keep track of where those |
| 40 | // enties exist in memory. |
Zane Shelley | fe27b65 | 2019-10-28 11:33:07 -0500 | [diff] [blame] | 41 | Foo* a[5]; |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 42 | 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 Shelley | 83da245 | 2019-10-25 15:45:34 -0500 | [diff] [blame] | 50 | for (int i = 4; i >= 0; i--) |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 51 | { |
Zane Shelley | 83da245 | 2019-10-25 15:45:34 -0500 | [diff] [blame] | 52 | ASSERT_EQ(a[i], &(addFoo(i))); |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 53 | } |
| 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 | } |