#include <k/io.h>
#include <k/core.h>
#include <k/def.h>
/* send.c - kiosend() "send to channel"
 * ~ lexi hale <lexi@hale.su>
 * kiosend() writes to a channel with an open out stream
 */

/* we define all platform functions here,
 * whether or not they're for the correct
 * platform - only the ones actually called
 * by the generated code will be linked */
#include <posix.h>

kiocond kiosend(kiochan target, ksraw string, sz* len) {
	if (target.out.kind == kiostream_closed) return kiocond_fail_closed_stream;

#	ifdef KFenv_posix
		/* issue the write syscall here and now so we can
		 * retrieve errno and report it if necessary */

		k_platform_syscall_arg args[] = {
			target.out.platform_fd, (k_platform_syscall_arg)string.ptr, string.size };

		struct k_platform_syscall_answer a = k_platform_syscall
			(k_platform_syscall_write,3,args);

		sz size = a.ret;
		if (size == -1) return kiocond_fail; //TODO: retrieve errno and offer more specific errors
#	else
#		if KVos == win
#			error windows IO send function not yet defined
#		else
			Knoimpl(kiosend,KVos);
#			error missing implementation // boring error for plebs
#		endif
#	endif

	if (len != null) *len = size;
	return kiocond_ok;
}
