/*
 * Simple IO functions
 *
 * These are just like read() and write(), except they will try
 * to process all the requested data, unless there's an error or
 * EOF.  They also cope with EINTR.
 *
 */

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>

#include "io.h"

int
fullread(int from, unsigned char *buf, size_t sz)
{
	int	rd = 0;
	int	ret;
	
	while(sz > 0)
	{
		ret = read(from, buf, sz);

		if (ret == -1)
		{
			if (errno == EINTR)
				continue;

			return -1;
		}

		if (ret == 0)
			break;
				
		sz -= ret;
		buf += ret;
		rd += ret;
	}

	return rd;
}

int
fullwrite(int tofd, const unsigned char *buf, size_t sz)
{
	int	wr = 0;
	int	ret;
	
	while(sz > 0)
	{
		ret = write(tofd, buf, sz);

		if (ret == -1)
		{
			if (errno == EINTR)
				continue;
			return -1;
		}

		if (ret == 0)
		{
			fprintf(stderr, "fullwrite wrote 0 bytes\n");
			break;
		}

		sz -= ret;
		buf += ret;
		wr += ret;
	}

	return wr;
}
