/*
 *
 *
 *    pipe.cc
 *
 *    C++ source code for class my::pipe member functions and/or static member
 *    data.
 *
 *    =========================================================================
 *
 *    Copyright (C) 1999-2003 by Matt Roberts, KK5JY.
 *
 *    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 <my++/pipe.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>


void my::pipeend::assign(int f, my::pipeend::mode m) {
	if (f >= 0) {
		close();
		fd = f;
		p_mode = m;
	} else {
		throw my::pipeend::exception(this, EINVAL);
	}
}


void my::pipe (my::pipeend &in, my::pipeend &out) {
	int fds[2];

	if (::pipe(fds) < 0)
		throw my::pipeend::exception(NULL, errno);

	in.assign (fds[0], my::pipeend::mode_read);
	out.assign(fds[1], my::pipeend::mode_write);
}


void my::pipe (my::pipeend &in, int &out) {
	int fds[2];

	if (::pipe(fds) < 0)
		throw my::pipeend::exception(NULL, errno);

	in.assign (fds[0], my::pipeend::mode_read);
	out = fds[1];
}


void my::pipe (int &in, my::pipeend &out) {
	int fds[2];

	if (::pipe(fds) < 0)
		throw my::pipeend::exception(NULL, errno);

	in = fds[0];
	out.assign(fds[1], my::pipeend::mode_write);
}


/*
 *
 *  close
 *
 */

void my::pipeend::close (void) throw() {
	if (fd >= 0) {
		::close(fd);
		fd = (-1);
	}
}


/*
 *
 *   I/O routines
 *
 */

ssize_t my::pipeend::read_vp (void *buf, size_t len) {
	return ::read (fd, buf, len);
}

ssize_t my::pipeend::write_vp (const void *buf, size_t len) {
	return ::write (fd, buf, len);
}


/*
 *
 *   public ctors
 *
 */

my::pipeend::pipeend (void) : fd(-1), p_mode(my::pipeend::mode_none) {
	/* noop */
}


/*
 *
 *   public dtor
 *
 */

my::pipeend::~pipeend (void) throw () {
	close();
}

/* EOF */
