SocketMonitor.cxx 1.82 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
#include "SocketMonitor.hxx"
#include "Loop.hxx"

#include <assert.h>

26
#ifdef _WIN32
27 28 29 30 31
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif

32
void
33
SocketMonitor::Dispatch(unsigned flags) noexcept
34 35 36 37 38 39 40
{
	flags &= GetScheduledFlags();

	if (flags != 0 && !OnSocketReady(flags) && IsDefined())
		Cancel();
}

41
SocketMonitor::~SocketMonitor() noexcept
42 43
{
	if (IsDefined())
44
		Cancel();
45 46
}

47
void
48
SocketMonitor::Open(SocketDescriptor _fd) noexcept
49
{
50 51
	assert(!fd.IsDefined());
	assert(_fd.IsDefined());
52 53 54 55

	fd = _fd;
}

56
SocketDescriptor
57
SocketMonitor::Steal() noexcept
58 59 60 61 62
{
	assert(IsDefined());

	Cancel();

63
	return std::exchange(fd, SocketDescriptor::Undefined());
64 65 66
}

void
67
SocketMonitor::Close() noexcept
68
{
69
	Steal().Close();
70
}
71

72
void
73
SocketMonitor::Schedule(unsigned flags) noexcept
74 75 76 77 78 79
{
	assert(IsDefined());

	if (flags == GetScheduledFlags())
		return;

80
	if (scheduled_flags == 0)
81
		loop.AddFD(fd.Get(), flags, *this);
82
	else if (flags == 0)
83
		loop.RemoveFD(fd.Get(), *this);
84
	else
85
		loop.ModifyFD(fd.Get(), flags, *this);
86 87

	scheduled_flags = flags;
88
}