#include <cassert>
#include <libfibre/cfibre.h>

typedef cfibre_t thread_t;
static_assert(sizeof(thread_t) == sizeof(void*), "thread_t musst be of same size as void*");

void * fibre_runner(void * arg) {
	auto the_main = (void (*)( thread_t ))arg;
	the_main( cfibre_self() );
	return nullptr;
}

extern "C" {
	//--------------------
	// Basic thread support
	thread_t thrdlib_create( void (*the_main)( thread_t ) ) {
		thread_t fibre;
		cfibre_create( &fibre, nullptr, fibre_runner, (void*)the_main );
		return fibre;
	}

	void thrdlib_join( thread_t handle ) {
		cfibre_join( handle, nullptr );
	}

	void thrdlib_park( thread_t handle ) {
		assert( handle == cfibre_self() );
		cfibre_park();
	}

	void thrdlib_unpark( thread_t handle ) {
		cfibre_unpark( handle );
	}

	void thrdlib_yield( void ) {
		cfibre_yield();
	}

	//--------------------
	// Basic kernel features
	void thrdlib_init( int procs ) {
		cfibre_init_n(1, procs );
	}

	void thrdlib_clean( void ) {

	}
}