algorithm_test.cpp 2.17 KB
Newer Older
1 2 3 4 5 6 7 8 9
#include <catch.hpp>
#include <array>

#include <pls/pls.h>

using namespace pls;

TEST_CASE("for_each functions correctly", "[algorithms/for_each.h]") {
  malloc_scheduler_memory my_scheduler_memory{8, 2 << 12};
10
  scheduler my_scheduler{&my_scheduler_memory, 8};
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
  my_scheduler.perform_work([]() {
    constexpr int SIZE = 1000;
    std::array<int, SIZE> result_array{};
    result_array.fill(0);

    SECTION("integer ranges are processed exactly once") {
      pls::for_each_range(0, SIZE, [&result_array](int i) {
        result_array[i]++;
      });

      bool all_equal = true;
      for (int i = 0; i < SIZE; i++) {
        all_equal &= result_array[i] == 1;
      }
      REQUIRE (all_equal);
    }

    SECTION("iterators are processed exactly once") {
      std::array<int, SIZE> iterator_array{};
      for (int i = 0; i < SIZE; i++) {
        iterator_array[i] = i;
      }

      pls::for_each(iterator_array.begin(), iterator_array.end(), [&result_array](int i) {
        result_array[i]++;
      });

      bool all_equal = true;
      for (int i = 0; i < SIZE; i++) {
        all_equal &= result_array[i] == 1;
      }
      REQUIRE (all_equal);
    }
  });
}
FritzFlorian committed
46 47 48

TEST_CASE("scan functions correctly", "[algorithms/scan.h]") {
  malloc_scheduler_memory my_scheduler_memory{8, 2 << 12};
49
  scheduler my_scheduler{&my_scheduler_memory, 8};
FritzFlorian committed
50
  my_scheduler.perform_work([]() {
51
    constexpr int SIZE = 10000;
FritzFlorian committed
52 53 54 55 56 57 58 59 60 61 62 63
    std::array<int, SIZE> input_array{}, result_array{};
    input_array.fill(1);

    pls::scan(input_array.begin(), input_array.end(), result_array.begin(), std::plus<int>(), 0);

    bool all_correct = true;
    for (int i = 0; i < SIZE; i++) {
      all_correct &= result_array[i] == (i + 1);
    }
    REQUIRE (all_correct);
  });
}
FritzFlorian committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

long fib(long n) {
  if (n <= 2) {
    return 1;
  }

  long a, b;

  pls::invoke(
      [&a, n]() { a = fib(n - 1); },
      [&b, n]() { b = fib(n - 2); }
  );

  return a + b;
}

TEST_CASE("invoke functions correctly", "[algorithms/invoke.h]") {
81
  constexpr long fib_30 = 832040;
FritzFlorian committed
82

83 84
  malloc_scheduler_memory my_scheduler_memory{8, 2u << 14};
  scheduler my_scheduler{&my_scheduler_memory, 8};
FritzFlorian committed
85
  my_scheduler.perform_work([=]() {
86
    REQUIRE(fib(30) == fib_30);
FritzFlorian committed
87 88
  });
}