Function.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright (C) 2009-2021, 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)>& f)
  10. {
  11. return f(1.0f) + f(2.0f);
  12. }
  13. } // end namespace anki
  14. ANKI_TEST(Util, Function)
  15. {
  16. HeapAllocator<U8> alloc(allocAligned, nullptr);
  17. // Simple
  18. {
  19. Function<I32(I32, F32), 8> f;
  20. I32 i = 0;
  21. f.init(alloc, [&i](U32 a, F32 b) -> I32 {
  22. i += I32(a) + I32(b);
  23. return i;
  24. });
  25. i = 1;
  26. f(2, 10.0f);
  27. ANKI_TEST_EXPECT_EQ(i, 13);
  28. f.destroy(alloc);
  29. }
  30. // No templates
  31. {
  32. F32 f = 1.1f;
  33. Function<I32(F32)> func(alloc, [&f](F32 ff) {
  34. f += 2.0f;
  35. return I32(f) + I32(ff);
  36. });
  37. const I32 o = functionAcceptingFunction(func);
  38. func.destroy(alloc);
  39. ANKI_TEST_EXPECT_EQ(o, 11);
  40. }
  41. // Allocated
  42. {
  43. const Vec4 a(1.9f);
  44. const Vec4 b(2.2f);
  45. Function<Vec4(Vec4, Vec4), 8> f(alloc, [a, b](Vec4 c, Vec4 d) mutable -> Vec4 {
  46. return a + c * 2.0f + b * d;
  47. });
  48. const Vec4 r = f(Vec4(10.0f), Vec4(20.8f));
  49. ANKI_TEST_EXPECT_EQ(r, a + Vec4(10.0f) * 2.0f + b * Vec4(20.8f));
  50. f.destroy(alloc);
  51. }
  52. // Complex
  53. {
  54. {
  55. Foo foo, bar;
  56. Function<void(Foo&)> f(alloc, [foo](Foo& r) {
  57. r.x += foo.x;
  58. });
  59. Function<void(Foo&)> ff;
  60. ff = std::move(f);
  61. ff(bar);
  62. ANKI_TEST_EXPECT_EQ(bar.x, 666 * 2);
  63. ff.destroy(alloc);
  64. }
  65. ANKI_TEST_EXPECT_EQ(Foo::constructorCallCount, Foo::destructorCallCount);
  66. Foo::reset();
  67. }
  68. // Copy
  69. {
  70. {
  71. Foo foo, bar;
  72. Function<void(Foo&)> f(alloc, [foo](Foo& r) {
  73. r.x += foo.x;
  74. });
  75. Function<void(Foo&)> ff;
  76. ff.copy(f, alloc);
  77. ff(bar);
  78. ANKI_TEST_EXPECT_EQ(bar.x, 666 * 2);
  79. ff.destroy(alloc);
  80. f.destroy(alloc);
  81. }
  82. ANKI_TEST_EXPECT_EQ(Foo::constructorCallCount, Foo::destructorCallCount);
  83. Foo::reset();
  84. }
  85. }