#pragma once

#include <cassert>
#include <cstddef>
#include <atomic>
#include <chrono>
#include <fstream>
#include <iostream>

#include <unistd.h>
#include <sys/sysinfo.h>

// Barrier from
class barrier_t {
public:
	barrier_t(size_t total)
		: waiting(0)
		, total(total)
	{}

	void wait(unsigned) {
		size_t target = waiting++;
		target = (target - (target % total)) + total;
		while(waiting < target)
			asm volatile("pause");

		assert(waiting < (1ul << 60));
    	}

private:
	std::atomic<size_t> waiting;
	size_t total;
};

class Random {
private:
	unsigned int seed;
public:
	Random(int seed) {
		this->seed = seed;
	}

	/** returns pseudorandom x satisfying 0 <= x < n. **/
	unsigned int next() {
		seed ^= seed << 6;
		seed ^= seed >> 21;
		seed ^= seed << 7;
		return seed;
    	}
};

static inline long long rdtscl(void) {
    unsigned int lo, hi;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}

void affinity(int tid) {
	static int cpus = get_nprocs();

	cpu_set_t  mask;
	CPU_ZERO(&mask);
	int cpu = cpus - tid;  // Set CPU affinity to tid, starting from the end
	CPU_SET(cpu, &mask);
	auto result = sched_setaffinity(0, sizeof(mask), &mask);
	if(result != 0) {
		std::cerr << "Affinity set failed with " << result<< ", wanted " << cpu << std::endl;
	}
}

static const constexpr std::size_t cache_line_size = 64;
void check_cache_line_size() {
	std::cout << "Checking cache line size" << std::endl;
	const std::string cache_file = "/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size";

	std::ifstream ifs (cache_file, std::ifstream::in);

	if(!ifs.good()) {
		std::cerr << "Could not open file to check cache line size" << std::endl;
		std::cerr << "Looking for: " << cache_file << std::endl;
		std::exit(2);
	}

	size_t got;
	ifs >> got;

	ifs.close();

	if(cache_line_size != got) {
		std::cerr << "Cache line has incorrect size : " << got << std::endl;
		std::exit(1);
	}

	std::cout << "Done" << std::endl;
}

using Clock = std::chrono::high_resolution_clock;
using duration_t = std::chrono::duration<double>;
using std::chrono::nanoseconds;

template<typename Ratio, typename T>
T duration_cast(T seconds) {
	return std::chrono::duration_cast<std::chrono::duration<T, Ratio>>(std::chrono::duration<T>(seconds)).count();
}