SocketMonitor.cxx 1.8 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 36 37 38 39
{
	flags &= GetScheduledFlags();

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

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
void
72
SocketMonitor::Schedule(unsigned flags) noexcept
73 74 75 76 77 78
{
	assert(IsDefined());

	if (flags == GetScheduledFlags())
		return;

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

	scheduled_flags = flags;
87
}