Function.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. ANKI_TEST(Util, Function)
  9. {
  10. HeapAllocator<U8> alloc(allocAligned, nullptr);
  11. // Simple
  12. {
  13. Function<I32(I32, F32), 8> f;
  14. I32 i = 0;
  15. f.init(alloc, [&i](U32 a, F32 b) -> I32 {
  16. i += I32(a) + I32(b);
  17. return i;
  18. });
  19. i = 1;
  20. f(2, 10.0f);
  21. ANKI_TEST_EXPECT_EQ(i, 13);
  22. f.destroy(alloc);
  23. }
  24. // Allocated
  25. {
  26. const Vec4 a(1.9f);
  27. const Vec4 b(2.2f);
  28. Function<Vec4(Vec4, Vec4), 8> f(alloc, [a, b](Vec4 c, Vec4 d) mutable -> Vec4 { return a + c * 2.0f + b * d; });
  29. const Vec4 r = f(Vec4(10.0f), Vec4(20.8f));
  30. ANKI_TEST_EXPECT_EQ(r, a + Vec4(10.0f) * 2.0f + b * Vec4(20.8f));
  31. f.destroy(alloc);
  32. }
  33. // Complex
  34. {
  35. {
  36. Foo foo, bar;
  37. Function<void(Foo&)> f(alloc, [foo](Foo& r) { r.x += foo.x; });
  38. Function<void(Foo&)> ff;
  39. ff = std::move(f);
  40. ff(bar);
  41. ANKI_TEST_EXPECT_EQ(bar.x, 666 * 2);
  42. ff.destroy(alloc);
  43. }
  44. ANKI_TEST_EXPECT_EQ(Foo::constructorCallCount, Foo::destructorCallCount);
  45. Foo::reset();
  46. }
  47. // Copy
  48. {
  49. {
  50. Foo foo, bar;
  51. Function<void(Foo&)> f(alloc, [foo](Foo& r) { r.x += foo.x; });
  52. Function<void(Foo&)> ff;
  53. ff.copy(f, alloc);
  54. ff(bar);
  55. ANKI_TEST_EXPECT_EQ(bar.x, 666 * 2);
  56. ff.destroy(alloc);
  57. f.destroy(alloc);
  58. }
  59. ANKI_TEST_EXPECT_EQ(Foo::constructorCallCount, Foo::destructorCallCount);
  60. Foo::reset();
  61. }
  62. }