Function.cpp 1.9 KB

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