/*
 *
 *
 *    select.cc
 *
 *    C++ source code for select 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 <algorithm>
#include <my++/select.h>


static inline int __local_max (int a, int b) {
	return (a > b) ? (a) : (b);
}

my::fdset::fdset(void) {
	FD_ZERO(&__fd_set);
}


my::fdset::fdset(const ::fd_set &f) {
	FD_ZERO(&__fd_set);
}


my::fdset::fdset(const my::fdset &f) {
	FD_ZERO(&__fd_set);
}


my::fdset &my::fdset::operator = (const ::fd_set &f) {
	if (&f != &__fd_set) {
		FD_ZERO(&__fd_set);
		__fd_set = f;
	}
	return (*this);
}


my::fdset &my::fdset::operator = (const my::fdset &f) {
	if (&(f.__fd_set) != &__fd_set) {
		FD_ZERO(&__fd_set);
		__fd_set = f.__fd_set;
	}
	return (*this);
}


int my::fdset::maxfd (void) {
	if (__fds.empty())
		return 0;
	return 1 + *std::max_element(__fds.begin(), __fds.end());
}


void my::fdset::rebuild(void) {
	std::list<int>::iterator i;

	FD_ZERO(&__fd_set);

	if (__fds.empty())
		return;

	for (i = __fds.begin(); i != __fds.end(); ++i)
		FD_SET(*i, &__fd_set);
}


int my::select (my::fdset *rs, my::fdset *ws, my::fdset *es, timeval *timeout) {
	int maxfd = 0;
	if (rs) maxfd = __local_max(maxfd, rs->maxfd()); 
	if (ws) maxfd = __local_max(maxfd, ws->maxfd()); 
	if (es) maxfd = __local_max(maxfd, es->maxfd()); 

	int result = ::select(
			maxfd,
			rs ? rs->c_set() : NULL,
			ws ? ws->c_set() : NULL,
			es ? es->c_set() : NULL,
			timeout);

	return result;
}

// EOF
