Function.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <Tests/Framework/Framework.h>
  6. #include <Tests/Util/Foo.h>
  7. #include <AnKi/Util/Function.h>
  8. namespace anki {
  9. static I32 functionAcceptingFunction(const Function<I32(F32), MemoryPoolPtrWrapper<HeapMemoryPool>>& f)
  10. {
  11. return f(1.0f) + f(2.0f);
  12. }
  13. } // end namespace anki
  14. ANKI_TEST(Util, Function)
  15. {
  16. HeapMemoryPool pool(allocAligned, nullptr);
  17. // Simple
  18. {
  19. I32 i = 0;
  20. Function<I32(I32, F32), MemoryPoolPtrWrapper<HeapMemoryPool>, 8> f(
  21. [&i](U32 a, F32 b) -> I32 {
  22. i += I32(a) + I32(b);
  23. return i;
  24. },
  25. &pool);
  26. i = 1;
  27. f(2, 10.0f);
  28. ANKI_TEST_EXPECT_EQ(i, 13);
  29. }
  30. // No templates
  31. {
  32. F32 f = 1.1f;
  33. Function<I32(F32), MemoryPoolPtrWrapper<HeapMemoryPool>> func(
  34. [&f](F32 ff) {
  35. f += 2.0f;
  36. return I32(f) + I32(ff);
  37. },
  38. &pool);
  39. const I32 o = functionAcceptingFunction(func);
  40. ANKI_TEST_EXPECT_EQ(o, 11);
  41. }
  42. // Allocated
  43. {
  44. const Vec4 a(1.9f);
  45. const Vec4 b(2.2f);
  46. Function<Vec4(Vec4, Vec4), MemoryPoolPtrWrapper<HeapMemoryPool>, 8> f(
  47. [a, b](Vec4 c, Vec4 d) mutable -> Vec4 {
  48. return a + c * 2.0f + b * d;
  49. },
  50. &pool);
  51. const Vec4 r = f(Vec4(10.0f), Vec4(20.8f));
  52. ANKI_TEST_EXPECT_EQ(r, a + Vec4(10.0f) * 2.0f + b * Vec4(20.8f));
  53. }
  54. // Complex
  55. {
  56. {
  57. Foo foo, bar;
  58. Function<void(Foo&), MemoryPoolPtrWrapper<HeapMemoryPool>> f(
  59. [foo](Foo& r) {
  60. r.x += foo.x;
  61. },
  62. &pool);
  63. Function<void(Foo&)> ff;
  64. ff = std::move(f);
  65. ff(bar);
  66. ANKI_TEST_EXPECT_EQ(bar.x, 666 * 2);
  67. }
  68. ANKI_TEST_EXPECT_EQ(Foo::constructorCallCount, Foo::destructorCallCount);
  69. Foo::reset();
  70. }
  71. // Copy
  72. {
  73. {
  74. Foo foo, bar;
  75. Function<void(Foo&), MemoryPoolPtrWrapper<HeapMemoryPool>> f(
  76. [foo](Foo& r) {
  77. r.x += foo.x;
  78. },
  79. &pool);
  80. Function<void(Foo&), MemoryPoolPtrWrapper<HeapMemoryPool>> ff;
  81. ff = f;
  82. ff(bar);
  83. ANKI_TEST_EXPECT_EQ(bar.x, 666 * 2);
  84. }
  85. ANKI_TEST_EXPECT_EQ(Foo::constructorCallCount, Foo::destructorCallCount);
  86. Foo::reset();
  87. }
  88. }