SocketMonitor.cxx 1.85 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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
 * 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 "SocketMonitor.hxx"
#include "Loop.hxx"

#include <assert.h>

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

31
void
32
SocketMonitor::Dispatch(unsigned flags) noexcept
33 34 35
{
	flags &= GetScheduledFlags();

36 37
	if (flags != 0)
		OnSocketReady(flags);
38 39
}

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

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

	fd = _fd;
}

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

	Cancel();

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

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

71
bool
72
SocketMonitor::Schedule(unsigned flags) noexcept
73 74 75 76
{
	assert(IsDefined());

	if (flags == GetScheduledFlags())
77
		return true;
78

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

	if (success)
		scheduled_flags = flags;
89

90
	return success;
91
}