#include "pls/internal/scheduling/scheduler_memory.h"

namespace pls {
namespace internal {
namespace scheduling {

malloc_scheduler_memory::malloc_scheduler_memory(const size_t num_threads, const size_t memory_per_stack) :
    num_threads_{num_threads} {
  threads_ =
      reinterpret_cast<aligned_thread *>(base::alignment::allocate_aligned(num_threads * sizeof(aligned_thread)));
  thread_states_ = reinterpret_cast<aligned_thread_state *>(base::alignment::allocate_aligned(
      num_threads * sizeof(aligned_thread_state)));

  task_stacks_ = reinterpret_cast<aligned_aligned_stack *>(base::alignment::allocate_aligned(
      num_threads * sizeof(aligned_aligned_stack)));
  task_stacks_memory_ = reinterpret_cast<char **>(base::alignment::allocate_aligned(num_threads * sizeof(char *)));
  for (size_t i = 0; i < num_threads_; i++) {
    task_stacks_memory_[i] = reinterpret_cast<char *>(base::alignment::allocate_aligned(memory_per_stack));
    new((void *) task_stacks_[i].pointer()) data_structures::aligned_stack(task_stacks_memory_[i], memory_per_stack);
  }
}

malloc_scheduler_memory::~malloc_scheduler_memory() {
  free(threads_);
  free(thread_states_);

  for (size_t i = 0; i < num_threads_; i++) {
    free(task_stacks_memory_[i]);
  }
  free(task_stacks_);
  free(task_stacks_memory_);
}

}
}
}
