/*
**  io.c
**
**  Copyright (c) 2004-2006
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**  
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
**  Lesser General Public License for more details.
**  
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <Pantomime/io.h>

#include <errno.h>
#ifdef __MINGW32__
#include <io.h> 	// For _read(), _write() and _close() on MinGW
#include <winsock2.h>	// For recv() on MinGW
#else
#include <sys/ioctl.h>
#include <sys/socket.h>
#endif

#include <unistd.h>	// For read(), write() and close()

#ifdef MACOSX
#include <sys/uio.h>	// For read() and write() on OS X
#endif

#if !defined(FIONBIO) && !defined(__MINGW32__)
#include <sys/filio.h>  // For FIONBIO on Solaris
#endif

//
//
//
ssize_t read_block(int fd, void *buf, size_t count)
{
  ssize_t tot, bytes;
  
  tot = bytes = 0;

  while (tot < count)
    {
#ifdef __MINGW32__ 
      if ((bytes = _read(fd, buf+tot, count-tot)) == -1)
#else
      if ((bytes = read(fd, buf+tot, count-tot)) == -1)
#endif
        {
	  if (errno != EINTR)
	    {
	      return -1;
	    }
	}
      else
	{
	  tot += bytes;
	}
    }
  
  return tot;
}


//
//
//
int safe_close(int fd)
{
  int value;
#ifdef __MINGW32__
  while (value = _close(fd), value == -1 && errno == EINTR);
#else
  while (value = close(fd), value == -1 && errno == EINTR);
#endif
  return value;
}

//
//
//
ssize_t safe_read(int fd, void *buf, size_t count)
{
  ssize_t value;
#ifdef __MINGW32__
  while (value = _read(fd, buf, count), value == -1 && errno == EINTR);
#else
  while (value = read(fd, buf, count), value == -1 && errno == EINTR);
#endif
  return value;
}

//
//
//
ssize_t safe_recv(int fd, void *buf, size_t count, int flags)
{
  ssize_t value;
  while (value = recv(fd, buf, count, flags), value == -1 && errno == EINTR);
  return value;
}
