<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED
#define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED

#include "libtorrent/socket.hpp"
#include "libtorrent/invariant_check.hpp"

#include <boost/shared_ptr.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/integer_traits.hpp>
#include <boost/thread/mutex.hpp>
#include <deque>

using boost::weak_ptr;
using boost::shared_ptr;
using boost::intrusive_ptr;
using boost::bind;

namespace libtorrent {

// the maximum block of bandwidth quota to
// hand out is 33kB. The block size may
// be smaller on lower limits
enum
{
	max_bandwidth_block_size = 33000,
	min_bandwidth_block_size = 400
};

const time_duration bw_window_size = seconds(1);

template<class PeerConnection, class Torrent>
struct history_entry
{
	history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t
		, int a, ptime exp)
		: expires_at(exp), amount(a), peer(p), tor(t) {}
	ptime expires_at;
	int amount;
	intrusive_ptr<PeerConnection> peer;
	weak_ptr<Torrent> tor;
};

template<class PeerConnection>
struct bw_queue_entry
{
	bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe
		, int blk, bool no_prio)
		: peer(pe), max_block_size(blk), non_prioritized(no_prio) {}
	boost::intrusive_ptr<PeerConnection> peer;
	int max_block_size;
	bool non_prioritized;
};

// member of peer_connection
struct bandwidth_limit
{
	static const int inf = boost::integer_traits<int>::const_max;

	bandwidth_limit() throw()
		: m_quota_left(0)
		, m_local_limit(inf)
		, m_current_rate(0)
	{}

	void throttle(int limit) throw()
	{
		m_local_limit = limit;
	}

	int throttle() const throw()
	{
		return m_local_limit;
	}

	void assign(int amount) throw()
	{
		assert(amount > 0);
		m_current_rate += amount;
		m_quota_left += amount;
	}

	void use_quota(int amount) throw()
	{
		assert(amount <= m_quota_left);
		m_quota_left -= amount;
	}

	int quota_left() const throw()
	{
		return (std::max)(m_quota_left, 0);
	}

	void expire(int amount) throw()
	{
		assert(amount >= 0);
		m_current_rate -= amount;
	}

	int max_assignable() const throw()
	{
		if (m_local_limit == inf) return inf;
		if (m_local_limit <= m_current_rate) return 0;
		return m_local_limit - m_current_rate;
	}

private:

	// this is the amount of bandwidth we have
	// been assigned without using yet. i.e.
	// the bandwidth that we use up every time
	// we receive or send a message. Once this
	// hits zero, we need to request more
	// bandwidth from the torrent which
	// in turn will request bandwidth from
	// the bandwidth manager
	int m_quota_left;

	// the local limit is the number of bytes
	// per window size we are allowed to use.
	int m_local_limit;

	// the current rate is the number of
	// bytes we have been assigned within
	// the window size.
	int m_current_rate;
};

template<class T>
T clamp(T val, T ceiling, T floor) throw()
{
	assert(ceiling >= floor);
	if (val >= ceiling) return ceiling;
	else if (val <= floor) return floor;
	return val;
}

template<class PeerConnection, class Torrent>
struct bandwidth_manager
{
	bandwidth_manager(io_service& ios, int channel) throw()
		: m_ios(ios)
		, m_history_timer(m_ios)
		, m_limit(bandwidth_limit::inf)
		, m_current_quota(0)
		, m_channel(channel)
	{}

	void throttle(int limit) throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		assert(limit >= 0);
		m_limit = limit;
	}

	int throttle() const throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_limit;
	}

	// non prioritized means that, if there's a line for bandwidth,
	// others will cut in front of the non-prioritized peers.
	// this is used by web seeds
	void request_bandwidth(intrusive_ptr<PeerConnection> peer
		, int blk
		, bool non_prioritized) throw()
	{
		INVARIANT_CHECK;
		assert(blk > 0);

		assert(!peer->ignore_bandwidth_limits());

		// make sure this peer isn't already in line
		// waiting for bandwidth
#ifndef NDEBUG
		for (typename queue_t::iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			assert(i->peer < peer || peer < i->peer);
		}
#endif

		assert(peer->max_assignable_bandwidth(m_channel) > 0);
		boost::shared_ptr<Torrent> t = peer->associated_torrent().lock();
		m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized));
		if (!non_prioritized)
		{
			typename queue_t::reverse_iterator i = m_queue.rbegin();
			typename queue_t::reverse_iterator j(i);
			for (++j; j != m_queue.rend(); ++j)
			{
				// if the peer's torrent is not the same one
				// continue looking for a peer from the same torrent
				if (j->peer->associated_torrent().lock() != t)
					continue;
				// if we found a peer from the same torrent that
				// is prioritized, there is no point looking
				// any further.
				if (!j->non_prioritized) break;

				using std::swap;
				swap(*i, *j);
				i = j;
			}
		}

		if (m_queue.size() == 1) hand_out_bandwidth();
	}

#ifndef NDEBUG
	void check_invariant() const
	{
		int current_quota = 0;
		for (typename history_t::const_iterator i
			= m_history.begin(), end(m_history.end()); i != end; ++i)
		{
			current_quota += i->amount;
		}

		assert(current_quota == m_current_quota);
	}
#endif

private:

	void add_history_entry(history_entry<PeerConnection, Torrent> const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;
		m_history.push_front(e);
		m_current_quota += e.amount;
		// in case the size > 1 there is already a timer
		// active that will be invoked, no need to set one up
		if (m_history.size() > 1) return;

		m_history_timer.expires_at(e.expires_at);
		m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
#ifndef NDEBUG
		}
		catch (std::exception&) { assert(false); }
#endif
	}

	void on_history_expire(asio::error_code const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		if (e) return;

		assert(!m_history.empty());

		ptime now(time_now());
		while (!m_history.empty() && m_history.back().expires_at <= now)
		{
			history_entry<PeerConnection, Torrent> e = m_history.back();
			m_history.pop_back();
			m_current_quota -= e.amount;
			assert(m_current_quota >= 0);
			intrusive_ptr<PeerConnection> c = e.peer;
			shared_ptr<Torrent> t = e.tor.lock();
			if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount);
			if (t) t->expire_bandwidth(m_channel, e.amount);
		}

		// now, wait for the next chunk to expire
		if (!m_history.empty())
		{
			m_history_timer.expires_at(m_history.back().expires_at);
			m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
		}

		// since some bandwidth just expired, it
		// means we can hand out more (in case there
		// are still consumers in line)
		if (!m_queue.empty()) hand_out_bandwidth();
#ifndef NDEBUG
		}
		catch (std::exception&)
		{
			assert(false);
		}
#endif
	}

	void hand_out_bandwidth() throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		ptime now(time_now());

		mutex_t::scoped_lock l(m_mutex);
		int limit = m_limit;
		l.unlock();

		// available bandwidth to hand out
		int amount = limit - m_current_quota;

		while (!m_queue.empty() && amount > 0)
		{
			assert(amount == limit - m_current_quota);
			bw_queue_entry<PeerConnection> qe = m_queue.front();
			m_queue.pop_front();

			shared_ptr<Torrent> t = qe.peer->associated_torrent().lock();
			if (!t) continue;
			if (qe.peer->is_disconnecting())
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// at this point, max_assignable may actually be zero. Since
			// the bandwidth quota is subtracted once the data has been
			// sent. If the peer was added to the queue while the data was
			// still being sent, max_assignable may have been > 0 at that time.
			int max_assignable = (std::min)(
				qe.peer->max_assignable_bandwidth(m_channel)
				, t->max_assignable_bandwidth(m_channel));
			if (max_assignable == 0)
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// this is the limit of the block size. It depends on the throttle
			// so that it can be closer to optimal. Larger block sizes will give lower
			// granularity to the rate but will be more efficient. At high rates
			// the block sizes are bigger and at low rates, the granularity
			// is more important and block sizes are smaller

			// the minimum rate that can be given is the block size, so, the
			// block size must be smaller for lower rates. This is because
			// the history window is one second, and the block will be forgotten
			// after one second.
			int block_size = (std::min)(qe.peer->bandwidth_throttle(m_channel)
				, m_limit / 10);

			if (block_size < min_bandwidth_block_size)
			{
				block_size = min_bandwidth_block_size;
			}
			else if (block_size > max_bandwidth_block_size)
			{
				if (m_limit == bandwidth_limit::inf)
				{
					block_size = max_bandwidth_block_size;
				}
				else
				{
					// try to make the block_size a divisor of
					// m_limit to make the distributions as fair
					// as possible
					// TODO: move this calculcation to where the limit
					// is changed
					block_size = m_limit
						/ (m_limit / max_bandwidth_block_size);
				}
			}
			if (block_size > qe.max_block_size) block_size = qe.max_block_size;

			if (amount < block_size / 2)
			{
				m_queue.push_front(qe);
				break;
			}

			// so, hand out max_assignable, but no more than
			// the available bandwidth (amount) and no more
			// than the max_bandwidth_block_size
			int hand_out_amount = (std::min)((std::min)(block_size, max_assignable)
				, amount);
			assert(hand_out_amount > 0);
			amount -= hand_out_amount;
			assert(hand_out_amount <= qe.max_block_size);
			t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size);
			qe.peer->assign_bandwidth(m_channel, hand_out_amount);
			add_history_entry(history_entry<PeerConnection, Torrent>(
				qe.peer, t, hand_out_amount, now + bw_window_size));
		}
#ifndef NDEBUG
		}
		catch (std::exception& e)
		{ assert(false); };
#endif
	}

	typedef boost::mutex mutex_t;
	mutable mutex_t m_mutex;

	// the io_service used for the timer
	io_service& m_ios;

	// the timer that is waiting for the entries
	// in the history queue to expire (slide out
	// of the history window)
	deadline_timer m_history_timer;

	// the rate limit (bytes per second)
	int m_limit;

	// the sum of all recently handed out bandwidth blocks
	int m_current_quota;

	// these are the consumers that want bandwidth
	typedef std::deque<bw_queue_entry<PeerConnection> > queue_t;
	queue_t m_queue;

	// these are the consumers that have received bandwidth
	// that will expire
	typedef std::deque<history_entry<PeerConnection, Torrent> > history_t;
	history_t m_history;

	// this is the channel within the consumers
	// that bandwidth is assigned to (upload or download)
	int m_channel;
};

}

#endif

<commit_msg>added assert to bandwidth_limiter<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED
#define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED

#include "libtorrent/socket.hpp"
#include "libtorrent/invariant_check.hpp"

#include <boost/shared_ptr.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/integer_traits.hpp>
#include <boost/thread/mutex.hpp>
#include <deque>

using boost::weak_ptr;
using boost::shared_ptr;
using boost::intrusive_ptr;
using boost::bind;

namespace libtorrent {

// the maximum block of bandwidth quota to
// hand out is 33kB. The block size may
// be smaller on lower limits
enum
{
	max_bandwidth_block_size = 33000,
	min_bandwidth_block_size = 400
};

const time_duration bw_window_size = seconds(1);

template<class PeerConnection, class Torrent>
struct history_entry
{
	history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t
		, int a, ptime exp)
		: expires_at(exp), amount(a), peer(p), tor(t) {}
	ptime expires_at;
	int amount;
	intrusive_ptr<PeerConnection> peer;
	weak_ptr<Torrent> tor;
};

template<class PeerConnection>
struct bw_queue_entry
{
	bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe
		, int blk, bool no_prio)
		: peer(pe), max_block_size(blk), non_prioritized(no_prio) {}
	boost::intrusive_ptr<PeerConnection> peer;
	int max_block_size;
	bool non_prioritized;
};

// member of peer_connection
struct bandwidth_limit
{
	static const int inf = boost::integer_traits<int>::const_max;

	bandwidth_limit() throw()
		: m_quota_left(0)
		, m_local_limit(inf)
		, m_current_rate(0)
	{}

	void throttle(int limit) throw()
	{
		m_local_limit = limit;
	}

	int throttle() const throw()
	{
		return m_local_limit;
	}

	void assign(int amount) throw()
	{
		assert(amount > 0);
		m_current_rate += amount;
		m_quota_left += amount;
	}

	void use_quota(int amount) throw()
	{
		assert(amount <= m_quota_left);
		m_quota_left -= amount;
	}

	int quota_left() const throw()
	{
		return (std::max)(m_quota_left, 0);
	}

	void expire(int amount) throw()
	{
		assert(amount >= 0);
		m_current_rate -= amount;
	}

	int max_assignable() const throw()
	{
		if (m_local_limit == inf) return inf;
		if (m_local_limit <= m_current_rate) return 0;
		return m_local_limit - m_current_rate;
	}

private:

	// this is the amount of bandwidth we have
	// been assigned without using yet. i.e.
	// the bandwidth that we use up every time
	// we receive or send a message. Once this
	// hits zero, we need to request more
	// bandwidth from the torrent which
	// in turn will request bandwidth from
	// the bandwidth manager
	int m_quota_left;

	// the local limit is the number of bytes
	// per window size we are allowed to use.
	int m_local_limit;

	// the current rate is the number of
	// bytes we have been assigned within
	// the window size.
	int m_current_rate;
};

template<class T>
T clamp(T val, T ceiling, T floor) throw()
{
	assert(ceiling >= floor);
	if (val >= ceiling) return ceiling;
	else if (val <= floor) return floor;
	return val;
}

template<class PeerConnection, class Torrent>
struct bandwidth_manager
{
	bandwidth_manager(io_service& ios, int channel) throw()
		: m_ios(ios)
		, m_history_timer(m_ios)
		, m_limit(bandwidth_limit::inf)
		, m_current_quota(0)
		, m_channel(channel)
	{}

	void throttle(int limit) throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		assert(limit >= 0);
		m_limit = limit;
	}

	int throttle() const throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_limit;
	}

	// non prioritized means that, if there's a line for bandwidth,
	// others will cut in front of the non-prioritized peers.
	// this is used by web seeds
	void request_bandwidth(intrusive_ptr<PeerConnection> peer
		, int blk
		, bool non_prioritized) throw()
	{
		INVARIANT_CHECK;
		assert(blk > 0);

		assert(!peer->ignore_bandwidth_limits());

		// make sure this peer isn't already in line
		// waiting for bandwidth
#ifndef NDEBUG
		for (typename queue_t::iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			assert(i->peer < peer || peer < i->peer);
		}
#endif

		assert(peer->max_assignable_bandwidth(m_channel) > 0);
		boost::shared_ptr<Torrent> t = peer->associated_torrent().lock();
		m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized));
		if (!non_prioritized)
		{
			typename queue_t::reverse_iterator i = m_queue.rbegin();
			typename queue_t::reverse_iterator j(i);
			for (++j; j != m_queue.rend(); ++j)
			{
				// if the peer's torrent is not the same one
				// continue looking for a peer from the same torrent
				if (j->peer->associated_torrent().lock() != t)
					continue;
				// if we found a peer from the same torrent that
				// is prioritized, there is no point looking
				// any further.
				if (!j->non_prioritized) break;

				using std::swap;
				swap(*i, *j);
				i = j;
			}
		}

		if (m_queue.size() == 1) hand_out_bandwidth();
	}

#ifndef NDEBUG
	void check_invariant() const
	{
		int current_quota = 0;
		for (typename history_t::const_iterator i
			= m_history.begin(), end(m_history.end()); i != end; ++i)
		{
			current_quota += i->amount;
		}

		assert(current_quota == m_current_quota);
	}
#endif

private:

	void add_history_entry(history_entry<PeerConnection, Torrent> const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;
		m_history.push_front(e);
		m_current_quota += e.amount;
		// in case the size > 1 there is already a timer
		// active that will be invoked, no need to set one up
		if (m_history.size() > 1) return;

		m_history_timer.expires_at(e.expires_at);
		m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
#ifndef NDEBUG
		}
		catch (std::exception&) { assert(false); }
#endif
	}

	void on_history_expire(asio::error_code const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		if (e) return;

		assert(!m_history.empty());

		ptime now(time_now());
		while (!m_history.empty() && m_history.back().expires_at <= now)
		{
			history_entry<PeerConnection, Torrent> e = m_history.back();
			m_history.pop_back();
			m_current_quota -= e.amount;
			assert(m_current_quota >= 0);
			intrusive_ptr<PeerConnection> c = e.peer;
			shared_ptr<Torrent> t = e.tor.lock();
			if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount);
			if (t) t->expire_bandwidth(m_channel, e.amount);
		}

		// now, wait for the next chunk to expire
		if (!m_history.empty())
		{
			m_history_timer.expires_at(m_history.back().expires_at);
			m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
		}

		// since some bandwidth just expired, it
		// means we can hand out more (in case there
		// are still consumers in line)
		if (!m_queue.empty()) hand_out_bandwidth();
#ifndef NDEBUG
		}
		catch (std::exception&)
		{
			assert(false);
		}
#endif
	}

	void hand_out_bandwidth() throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		ptime now(time_now());

		mutex_t::scoped_lock l(m_mutex);
		int limit = m_limit;
		l.unlock();

		// available bandwidth to hand out
		int amount = limit - m_current_quota;

		while (!m_queue.empty() && amount > 0)
		{
			assert(amount == limit - m_current_quota);
			bw_queue_entry<PeerConnection> qe = m_queue.front();
			assert(qe.max_bock_size > 0);
			m_queue.pop_front();

			shared_ptr<Torrent> t = qe.peer->associated_torrent().lock();
			if (!t) continue;
			if (qe.peer->is_disconnecting())
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// at this point, max_assignable may actually be zero. Since
			// the bandwidth quota is subtracted once the data has been
			// sent. If the peer was added to the queue while the data was
			// still being sent, max_assignable may have been > 0 at that time.
			int max_assignable = (std::min)(
				qe.peer->max_assignable_bandwidth(m_channel)
				, t->max_assignable_bandwidth(m_channel));
			if (max_assignable == 0)
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// this is the limit of the block size. It depends on the throttle
			// so that it can be closer to optimal. Larger block sizes will give lower
			// granularity to the rate but will be more efficient. At high rates
			// the block sizes are bigger and at low rates, the granularity
			// is more important and block sizes are smaller

			// the minimum rate that can be given is the block size, so, the
			// block size must be smaller for lower rates. This is because
			// the history window is one second, and the block will be forgotten
			// after one second.
			int block_size = (std::min)(qe.peer->bandwidth_throttle(m_channel)
				, m_limit / 10);

			if (block_size < min_bandwidth_block_size)
			{
				block_size = min_bandwidth_block_size;
			}
			else if (block_size > max_bandwidth_block_size)
			{
				if (m_limit == bandwidth_limit::inf)
				{
					block_size = max_bandwidth_block_size;
				}
				else
				{
					// try to make the block_size a divisor of
					// m_limit to make the distributions as fair
					// as possible
					// TODO: move this calculcation to where the limit
					// is changed
					block_size = m_limit
						/ (m_limit / max_bandwidth_block_size);
				}
			}
			if (block_size > qe.max_block_size) block_size = qe.max_block_size;

			if (amount < block_size / 2)
			{
				m_queue.push_front(qe);
				break;
			}

			// so, hand out max_assignable, but no more than
			// the available bandwidth (amount) and no more
			// than the max_bandwidth_block_size
			int hand_out_amount = (std::min)((std::min)(block_size, max_assignable)
				, amount);
			assert(hand_out_amount > 0);
			amount -= hand_out_amount;
			assert(hand_out_amount <= qe.max_block_size);
			t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size);
			qe.peer->assign_bandwidth(m_channel, hand_out_amount);
			add_history_entry(history_entry<PeerConnection, Torrent>(
				qe.peer, t, hand_out_amount, now + bw_window_size));
		}
#ifndef NDEBUG
		}
		catch (std::exception& e)
		{ assert(false); };
#endif
	}

	typedef boost::mutex mutex_t;
	mutable mutex_t m_mutex;

	// the io_service used for the timer
	io_service& m_ios;

	// the timer that is waiting for the entries
	// in the history queue to expire (slide out
	// of the history window)
	deadline_timer m_history_timer;

	// the rate limit (bytes per second)
	int m_limit;

	// the sum of all recently handed out bandwidth blocks
	int m_current_quota;

	// these are the consumers that want bandwidth
	typedef std::deque<bw_queue_entry<PeerConnection> > queue_t;
	queue_t m_queue;

	// these are the consumers that have received bandwidth
	// that will expire
	typedef std::deque<history_entry<PeerConnection, Torrent> > history_t;
	history_t m_history;

	// this is the channel within the consumers
	// that bandwidth is assigned to (upload or download)
	int m_channel;
};

}

#endif

<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED
#define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED

#include "libtorrent/socket.hpp"
#include "libtorrent/invariant_check.hpp"

#include <boost/shared_ptr.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/integer_traits.hpp>
#include <boost/thread/mutex.hpp>
#include <deque>

using boost::weak_ptr;
using boost::shared_ptr;
using boost::intrusive_ptr;
using boost::bind;

namespace libtorrent {

// the maximum block of bandwidth quota to
// hand out is 33kB. The block size may
// be smaller on lower limits
enum
{
	max_bandwidth_block_size = 33000,
	min_bandwidth_block_size = 400
};

const time_duration bw_window_size = seconds(1);

template<class PeerConnection, class Torrent>
struct history_entry
{
	history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t
		, int a, ptime exp)
		: expires_at(exp), amount(a), peer(p), tor(t) {}
	ptime expires_at;
	int amount;
	intrusive_ptr<PeerConnection> peer;
	weak_ptr<Torrent> tor;
};

template<class PeerConnection>
struct bw_queue_entry
{
	bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe
		, int blk, bool no_prio)
		: peer(pe), max_block_size(blk), non_prioritized(no_prio) {}
	boost::intrusive_ptr<PeerConnection> peer;
	int max_block_size;
	bool non_prioritized;
};

// member of peer_connection
struct bandwidth_limit
{
	static const int inf = boost::integer_traits<int>::const_max;

	bandwidth_limit() throw()
		: m_quota_left(0)
		, m_local_limit(inf)
		, m_current_rate(0)
	{}

	void throttle(int limit) throw()
	{
		m_local_limit = limit;
	}

	int throttle() const throw()
	{
		return m_local_limit;
	}

	void assign(int amount) throw()
	{
		assert(amount > 0);
		m_current_rate += amount;
		m_quota_left += amount;
	}

	void use_quota(int amount) throw()
	{
		assert(amount <= m_quota_left);
		m_quota_left -= amount;
	}

	int quota_left() const throw()
	{
		return (std::max)(m_quota_left, 0);
	}

	void expire(int amount) throw()
	{
		assert(amount >= 0);
		m_current_rate -= amount;
	}

	int max_assignable() const throw()
	{
		if (m_local_limit == inf) return inf;
		if (m_local_limit <= m_current_rate) return 0;
		return m_local_limit - m_current_rate;
	}

private:

	// this is the amount of bandwidth we have
	// been assigned without using yet. i.e.
	// the bandwidth that we use up every time
	// we receive or send a message. Once this
	// hits zero, we need to request more
	// bandwidth from the torrent which
	// in turn will request bandwidth from
	// the bandwidth manager
	int m_quota_left;

	// the local limit is the number of bytes
	// per window size we are allowed to use.
	int m_local_limit;

	// the current rate is the number of
	// bytes we have been assigned within
	// the window size.
	int m_current_rate;
};

template<class T>
T clamp(T val, T ceiling, T floor) throw()
{
	assert(ceiling >= floor);
	if (val >= ceiling) return ceiling;
	else if (val <= floor) return floor;
	return val;
}

template<class PeerConnection, class Torrent>
struct bandwidth_manager
{
	bandwidth_manager(io_service& ios, int channel) throw()
		: m_ios(ios)
		, m_history_timer(m_ios)
		, m_limit(bandwidth_limit::inf)
		, m_current_quota(0)
		, m_channel(channel)
	{}

	void throttle(int limit) throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		assert(limit >= 0);
		m_limit = limit;
	}

	int throttle() const throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_limit;
	}

	// non prioritized means that, if there's a line for bandwidth,
	// others will cut in front of the non-prioritized peers.
	// this is used by web seeds
	void request_bandwidth(intrusive_ptr<PeerConnection> peer
		, int blk
		, bool non_prioritized) throw()
	{
		INVARIANT_CHECK;
		assert(blk > 0);

		assert(!peer->ignore_bandwidth_limits());

		// make sure this peer isn't already in line
		// waiting for bandwidth
#ifndef NDEBUG
		for (typename queue_t::iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			assert(i->peer < peer || peer < i->peer);
		}
#endif

		assert(peer->max_assignable_bandwidth(m_channel) > 0);
		boost::shared_ptr<Torrent> t = peer->associated_torrent().lock();
		m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized));
		if (!non_prioritized)
		{
			typename queue_t::reverse_iterator i = m_queue.rbegin();
			typename queue_t::reverse_iterator j(i);
			for (++j; j != m_queue.rend(); ++j)
			{
				// if the peer's torrent is not the same one
				// continue looking for a peer from the same torrent
				if (j->peer->associated_torrent().lock() != t)
					continue;
				// if we found a peer from the same torrent that
				// is prioritized, there is no point looking
				// any further.
				if (!j->non_prioritized) break;

				using std::swap;
				swap(*i, *j);
				i = j;
			}
		}

		if (m_queue.size() == 1) hand_out_bandwidth();
	}

#ifndef NDEBUG
	void check_invariant() const
	{
		int current_quota = 0;
		for (typename history_t::const_iterator i
			= m_history.begin(), end(m_history.end()); i != end; ++i)
		{
			current_quota += i->amount;
		}

		assert(current_quota == m_current_quota);
	}
#endif

private:

	void add_history_entry(history_entry<PeerConnection, Torrent> const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;
		m_history.push_front(e);
		m_current_quota += e.amount;
		// in case the size > 1 there is already a timer
		// active that will be invoked, no need to set one up
		if (m_history.size() > 1) return;

		m_history_timer.expires_at(e.expires_at);
		m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
#ifndef NDEBUG
		}
		catch (std::exception&) { assert(false); }
#endif
	}

	void on_history_expire(asio::error_code const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		if (e) return;

		assert(!m_history.empty());

		ptime now(time_now());
		while (!m_history.empty() && m_history.back().expires_at <= now)
		{
			history_entry<PeerConnection, Torrent> e = m_history.back();
			m_history.pop_back();
			m_current_quota -= e.amount;
			assert(m_current_quota >= 0);
			intrusive_ptr<PeerConnection> c = e.peer;
			shared_ptr<Torrent> t = e.tor.lock();
			if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount);
			if (t) t->expire_bandwidth(m_channel, e.amount);
		}

		// now, wait for the next chunk to expire
		if (!m_history.empty())
		{
			m_history_timer.expires_at(m_history.back().expires_at);
			m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
		}

		// since some bandwidth just expired, it
		// means we can hand out more (in case there
		// are still consumers in line)
		if (!m_queue.empty()) hand_out_bandwidth();
#ifndef NDEBUG
		}
		catch (std::exception&)
		{
			assert(false);
		}
#endif
	}

	void hand_out_bandwidth() throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		ptime now(time_now());

		mutex_t::scoped_lock l(m_mutex);
		int limit = m_limit;
		l.unlock();

		// available bandwidth to hand out
		int amount = limit - m_current_quota;

		while (!m_queue.empty() && amount > 0)
		{
			assert(amount == limit - m_current_quota);
			bw_queue_entry<PeerConnection> qe = m_queue.front();
			m_queue.pop_front();

			shared_ptr<Torrent> t = qe.peer->associated_torrent().lock();
			if (!t) continue;
			if (qe.peer->is_disconnecting())
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// at this point, max_assignable may actually be zero. Since
			// the bandwidth quota is subtracted once the data has been
			// sent. If the peer was added to the queue while the data was
			// still being sent, max_assignable may have been > 0 at that time.
			int max_assignable = (std::min)(
				qe.peer->max_assignable_bandwidth(m_channel)
				, t->max_assignable_bandwidth(m_channel));
			if (max_assignable == 0)
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// this is the limit of the block size. It depends on the throttle
			// so that it can be closer to optimal. Larger block sizes will give lower
			// granularity to the rate but will be more efficient. At high rates
			// the block sizes are bigger and at low rates, the granularity
			// is more important and block sizes are smaller

			// the minimum rate that can be given is the block size, so, the
			// block size must be smaller for lower rates. This is because
			// the history window is one second, and the block will be forgotten
			// after one second.
			int block_size = (std::min)(qe.max_block_size
				, (std::min)(qe.peer->bandwidth_throttle(m_channel)
				, m_limit / 10));

			if (block_size < min_bandwidth_block_size)
			{
				block_size = min_bandwidth_block_size;
			}
			else if (block_size > max_bandwidth_block_size)
			{
				if (m_limit == bandwidth_limit::inf)
				{
					block_size = max_bandwidth_block_size;
				}
				else
				{
					// try to make the block_size a divisor of
					// m_limit to make the distributions as fair
					// as possible
					// TODO: move this calculcation to where the limit
					// is changed
					block_size = m_limit
						/ (m_limit / max_bandwidth_block_size);
				}
				if (block_size > qe.max_block_size) block_size = qe.max_block_size;
			}

			if (amount < block_size / 2)
			{
				m_queue.push_front(qe);
				break;
			}

			// so, hand out max_assignable, but no more than
			// the available bandwidth (amount) and no more
			// than the max_bandwidth_block_size
			int hand_out_amount = (std::min)((std::min)(block_size, max_assignable)
				, amount);
			assert(hand_out_amount > 0);
			amount -= hand_out_amount;
			assert(hand_out_amount <= qe.max_block_size);
			t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size);
			qe.peer->assign_bandwidth(m_channel, hand_out_amount);
			add_history_entry(history_entry<PeerConnection, Torrent>(
				qe.peer, t, hand_out_amount, now + bw_window_size));
		}
#ifndef NDEBUG
		}
		catch (std::exception& e)
		{ assert(false); };
#endif
	}

	typedef boost::mutex mutex_t;
	mutable mutex_t m_mutex;

	// the io_service used for the timer
	io_service& m_ios;

	// the timer that is waiting for the entries
	// in the history queue to expire (slide out
	// of the history window)
	deadline_timer m_history_timer;

	// the rate limit (bytes per second)
	int m_limit;

	// the sum of all recently handed out bandwidth blocks
	int m_current_quota;

	// these are the consumers that want bandwidth
	typedef std::deque<bw_queue_entry<PeerConnection> > queue_t;
	queue_t m_queue;

	// these are the consumers that have received bandwidth
	// that will expire
	typedef std::deque<history_entry<PeerConnection, Torrent> > history_t;
	history_t m_history;

	// this is the channel within the consumers
	// that bandwidth is assigned to (upload or download)
	int m_channel;
};

}

#endif

<commit_msg>rate limiter fix<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED
#define TORRENT_BANDWIDTH_MANAGER_HPP_INCLUDED

#include "libtorrent/socket.hpp"
#include "libtorrent/invariant_check.hpp"

#include <boost/shared_ptr.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/integer_traits.hpp>
#include <boost/thread/mutex.hpp>
#include <deque>

using boost::weak_ptr;
using boost::shared_ptr;
using boost::intrusive_ptr;
using boost::bind;

namespace libtorrent {

// the maximum block of bandwidth quota to
// hand out is 33kB. The block size may
// be smaller on lower limits
enum
{
	max_bandwidth_block_size = 33000,
	min_bandwidth_block_size = 400
};

const time_duration bw_window_size = seconds(1);

template<class PeerConnection, class Torrent>
struct history_entry
{
	history_entry(intrusive_ptr<PeerConnection> p, weak_ptr<Torrent> t
		, int a, ptime exp)
		: expires_at(exp), amount(a), peer(p), tor(t) {}
	ptime expires_at;
	int amount;
	intrusive_ptr<PeerConnection> peer;
	weak_ptr<Torrent> tor;
};

template<class PeerConnection>
struct bw_queue_entry
{
	bw_queue_entry(boost::intrusive_ptr<PeerConnection> const& pe
		, int blk, bool no_prio)
		: peer(pe), max_block_size(blk), non_prioritized(no_prio) {}
	boost::intrusive_ptr<PeerConnection> peer;
	int max_block_size;
	bool non_prioritized;
};

// member of peer_connection
struct bandwidth_limit
{
	static const int inf = boost::integer_traits<int>::const_max;

	bandwidth_limit() throw()
		: m_quota_left(0)
		, m_local_limit(inf)
		, m_current_rate(0)
	{}

	void throttle(int limit) throw()
	{
		m_local_limit = limit;
	}

	int throttle() const throw()
	{
		return m_local_limit;
	}

	void assign(int amount) throw()
	{
		assert(amount > 0);
		m_current_rate += amount;
		m_quota_left += amount;
	}

	void use_quota(int amount) throw()
	{
		assert(amount <= m_quota_left);
		m_quota_left -= amount;
	}

	int quota_left() const throw()
	{
		return (std::max)(m_quota_left, 0);
	}

	void expire(int amount) throw()
	{
		assert(amount >= 0);
		m_current_rate -= amount;
	}

	int max_assignable() const throw()
	{
		if (m_local_limit == inf) return inf;
		if (m_local_limit <= m_current_rate) return 0;
		return m_local_limit - m_current_rate;
	}

private:

	// this is the amount of bandwidth we have
	// been assigned without using yet. i.e.
	// the bandwidth that we use up every time
	// we receive or send a message. Once this
	// hits zero, we need to request more
	// bandwidth from the torrent which
	// in turn will request bandwidth from
	// the bandwidth manager
	int m_quota_left;

	// the local limit is the number of bytes
	// per window size we are allowed to use.
	int m_local_limit;

	// the current rate is the number of
	// bytes we have been assigned within
	// the window size.
	int m_current_rate;
};

template<class T>
T clamp(T val, T ceiling, T floor) throw()
{
	assert(ceiling >= floor);
	if (val >= ceiling) return ceiling;
	else if (val <= floor) return floor;
	return val;
}

template<class PeerConnection, class Torrent>
struct bandwidth_manager
{
	bandwidth_manager(io_service& ios, int channel) throw()
		: m_ios(ios)
		, m_history_timer(m_ios)
		, m_limit(bandwidth_limit::inf)
		, m_current_quota(0)
		, m_channel(channel)
	{}

	void throttle(int limit) throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		assert(limit >= 0);
		m_limit = limit;
	}

	int throttle() const throw()
	{
		mutex_t::scoped_lock l(m_mutex);
		return m_limit;
	}

	// non prioritized means that, if there's a line for bandwidth,
	// others will cut in front of the non-prioritized peers.
	// this is used by web seeds
	void request_bandwidth(intrusive_ptr<PeerConnection> peer
		, int blk
		, bool non_prioritized) throw()
	{
		INVARIANT_CHECK;
		assert(blk > 0);

		assert(!peer->ignore_bandwidth_limits());

		// make sure this peer isn't already in line
		// waiting for bandwidth
#ifndef NDEBUG
		for (typename queue_t::iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			assert(i->peer < peer || peer < i->peer);
		}
#endif

		assert(peer->max_assignable_bandwidth(m_channel) > 0);
		boost::shared_ptr<Torrent> t = peer->associated_torrent().lock();
		m_queue.push_back(bw_queue_entry<PeerConnection>(peer, blk, non_prioritized));
		if (!non_prioritized)
		{
			typename queue_t::reverse_iterator i = m_queue.rbegin();
			typename queue_t::reverse_iterator j(i);
			for (++j; j != m_queue.rend(); ++j)
			{
				// if the peer's torrent is not the same one
				// continue looking for a peer from the same torrent
				if (j->peer->associated_torrent().lock() != t)
					continue;
				// if we found a peer from the same torrent that
				// is prioritized, there is no point looking
				// any further.
				if (!j->non_prioritized) break;

				using std::swap;
				swap(*i, *j);
				i = j;
			}
		}

		if (m_queue.size() == 1) hand_out_bandwidth();
	}

#ifndef NDEBUG
	void check_invariant() const
	{
		int current_quota = 0;
		for (typename history_t::const_iterator i
			= m_history.begin(), end(m_history.end()); i != end; ++i)
		{
			current_quota += i->amount;
		}

		assert(current_quota == m_current_quota);
	}
#endif

private:

	void add_history_entry(history_entry<PeerConnection, Torrent> const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;
		m_history.push_front(e);
		m_current_quota += e.amount;
		// in case the size > 1 there is already a timer
		// active that will be invoked, no need to set one up
		if (m_history.size() > 1) return;

		m_history_timer.expires_at(e.expires_at);
		m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
#ifndef NDEBUG
		}
		catch (std::exception&) { assert(false); }
#endif
	}

	void on_history_expire(asio::error_code const& e) throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		if (e) return;

		assert(!m_history.empty());

		ptime now(time_now());
		while (!m_history.empty() && m_history.back().expires_at <= now)
		{
			history_entry<PeerConnection, Torrent> e = m_history.back();
			m_history.pop_back();
			m_current_quota -= e.amount;
			assert(m_current_quota >= 0);
			intrusive_ptr<PeerConnection> c = e.peer;
			shared_ptr<Torrent> t = e.tor.lock();
			if (!c->is_disconnecting()) c->expire_bandwidth(m_channel, e.amount);
			if (t) t->expire_bandwidth(m_channel, e.amount);
		}

		// now, wait for the next chunk to expire
		if (!m_history.empty())
		{
			m_history_timer.expires_at(m_history.back().expires_at);
			m_history_timer.async_wait(bind(&bandwidth_manager::on_history_expire, this, _1));
		}

		// since some bandwidth just expired, it
		// means we can hand out more (in case there
		// are still consumers in line)
		if (!m_queue.empty()) hand_out_bandwidth();
#ifndef NDEBUG
		}
		catch (std::exception&)
		{
			assert(false);
		}
#endif
	}

	void hand_out_bandwidth() throw()
	{
#ifndef NDEBUG
		try {
#endif
		INVARIANT_CHECK;

		ptime now(time_now());

		mutex_t::scoped_lock l(m_mutex);
		int limit = m_limit;
		l.unlock();

		// available bandwidth to hand out
		int amount = limit - m_current_quota;

		while (!m_queue.empty() && amount > 0)
		{
			assert(amount == limit - m_current_quota);
			bw_queue_entry<PeerConnection> qe = m_queue.front();
			m_queue.pop_front();

			shared_ptr<Torrent> t = qe.peer->associated_torrent().lock();
			if (!t) continue;
			if (qe.peer->is_disconnecting())
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// at this point, max_assignable may actually be zero. Since
			// the bandwidth quota is subtracted once the data has been
			// sent. If the peer was added to the queue while the data was
			// still being sent, max_assignable may have been > 0 at that time.
			int max_assignable = (std::min)(
				qe.peer->max_assignable_bandwidth(m_channel)
				, t->max_assignable_bandwidth(m_channel));
			if (max_assignable == 0)
			{
				t->expire_bandwidth(m_channel, qe.max_block_size);
				continue;
			}

			// this is the limit of the block size. It depends on the throttle
			// so that it can be closer to optimal. Larger block sizes will give lower
			// granularity to the rate but will be more efficient. At high rates
			// the block sizes are bigger and at low rates, the granularity
			// is more important and block sizes are smaller

			// the minimum rate that can be given is the block size, so, the
			// block size must be smaller for lower rates. This is because
			// the history window is one second, and the block will be forgotten
			// after one second.
			int block_size = (std::min)(qe.peer->bandwidth_throttle(m_channel)
				, m_limit / 10);

			if (block_size < min_bandwidth_block_size)
			{
				block_size = min_bandwidth_block_size;
			}
			else if (block_size > max_bandwidth_block_size)
			{
				if (m_limit == bandwidth_limit::inf)
				{
					block_size = max_bandwidth_block_size;
				}
				else
				{
					// try to make the block_size a divisor of
					// m_limit to make the distributions as fair
					// as possible
					// TODO: move this calculcation to where the limit
					// is changed
					block_size = m_limit
						/ (m_limit / max_bandwidth_block_size);
				}
			}
			if (block_size > qe.max_block_size) block_size = qe.max_block_size;

			if (amount < block_size / 2)
			{
				m_queue.push_front(qe);
				break;
			}

			// so, hand out max_assignable, but no more than
			// the available bandwidth (amount) and no more
			// than the max_bandwidth_block_size
			int hand_out_amount = (std::min)((std::min)(block_size, max_assignable)
				, amount);
			assert(hand_out_amount > 0);
			amount -= hand_out_amount;
			assert(hand_out_amount <= qe.max_block_size);
			t->assign_bandwidth(m_channel, hand_out_amount, qe.max_block_size);
			qe.peer->assign_bandwidth(m_channel, hand_out_amount);
			add_history_entry(history_entry<PeerConnection, Torrent>(
				qe.peer, t, hand_out_amount, now + bw_window_size));
		}
#ifndef NDEBUG
		}
		catch (std::exception& e)
		{ assert(false); };
#endif
	}

	typedef boost::mutex mutex_t;
	mutable mutex_t m_mutex;

	// the io_service used for the timer
	io_service& m_ios;

	// the timer that is waiting for the entries
	// in the history queue to expire (slide out
	// of the history window)
	deadline_timer m_history_timer;

	// the rate limit (bytes per second)
	int m_limit;

	// the sum of all recently handed out bandwidth blocks
	int m_current_quota;

	// these are the consumers that want bandwidth
	typedef std::deque<bw_queue_entry<PeerConnection> > queue_t;
	queue_t m_queue;

	// these are the consumers that have received bandwidth
	// that will expire
	typedef std::deque<history_entry<PeerConnection, Torrent> > history_t;
	history_t m_history;

	// this is the channel within the consumers
	// that bandwidth is assigned to (upload or download)
	int m_channel;
};

}

#endif

<|endoftext|>


<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GAME_EDITOR_EDITOR_HPP
#define RJ_GAME_EDITOR_EDITOR_HPP

#include "background_editor.hpp"
#include "editor_entity.hpp"
#include "itembar.hpp"
#include "mouse.hpp"
#include <rectojump/game/components/platfrom.hpp>
#include <rectojump/game/camera.hpp>
#include <rectojump/game/world.hpp>

namespace rj
{
	template<typename Game_Handler, typename Game>
	class editor
	{
		Game_Handler& m_gamehandler;
		Game& m_game;
		world& m_gameworld;
		entity_handler& m_entityhandler;

		camera m_editarea_camera;
		camera m_itembar_camera;

		static constexpr float m_itembar_height{100.f};
		editor_mouse m_mouse;
		background_editor<editor> m_background{*this};
		itembar<Game_Handler> m_itembar;

	public:
		editor(Game_Handler& gh) :
			m_gamehandler{gh},
			m_game{gh.get_game()},
			m_gameworld{m_game.get_world()},
			m_entityhandler{m_gameworld.get_entityhandler()},
			m_editarea_camera{m_gamehandler.get_gamewindow()},
			m_itembar_camera{m_gamehandler.get_gamewindow()},
			m_mouse{gh.get_render()},
			m_itembar{gh, {settings::get_window_size<vec2f>().x, m_itembar_height}}
		{this->init();}

		void update(dur duration)
		{
			// edit area
			m_editarea_camera.set_changes();
			m_mouse.update(duration);

			// itembar
			m_itembar_camera.set_changes();
			m_itembar.update(duration);
		}

		void render()
		{
			// edit area
			m_editarea_camera.set_changes();
			m_entityhandler.render();
			m_mouse.render();

			// itembar
			m_itembar_camera.set_changes();
			m_itembar.render();
		}

		void on_activate()
		{
			m_background.reset();
		}

		auto get_gamehandler() noexcept
		-> decltype(m_gamehandler)&
		{return m_gamehandler;}

	private:
		void init()
		{
			m_itembar.on_item_click = [this](base_btn_ptr& b){m_mouse.set_texture(b->get_texture());};

			this->init_input();
			this->init_cameras();
		}

		void init_input()
		{
			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos){this->on_mouse_left(pos);}, btn::Left);

			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos){this->on_mouse_right(pos);}, btn::Right);

			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos){m_editarea_camera.move({10.2f, 0.f});}, wheel::down);

			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos)
			{
				if(m_editarea_camera.get_center().x >= m_editarea_camera.get_startcenter().x)
					m_editarea_camera.move({-10.5f, 0.f});
			}, wheel::up);
		}

		void init_cameras() noexcept
		{
			auto window_size(settings::get_window_size<vec2f>());

			float itembar_top{(window_size.y - m_itembar_height) / window_size.y};
			float itembar_height{m_itembar_height / window_size.y};
			float editarea_height{(window_size.y - m_itembar_height) / window_size.y};

			sf::View editarea_view{vec2f{window_size.x, window_size.y - m_itembar_height} / 2.f, {window_size.x, window_size.y - m_itembar_height}};
			editarea_view.setViewport({0.f, 0.f, 1.f ,editarea_height});
			m_editarea_camera.set_view(editarea_view);

			sf::View itembar_view{vec2f{window_size.x, m_itembar_height} / 2.f, {window_size.x, m_itembar_height}};
			itembar_view.setViewport({0.f, itembar_top, 1.f, itembar_height});
			m_itembar_camera.set_view(itembar_view);
		}

		void on_mouse_left(const vec2f&)
		{
			auto mouse_bounds(bounds_from_vec(m_itembar_camera.get_mapped_mousepos()));
			if(mouse_bounds.intersects(m_itembar.get_bounds()))
				return;

			float f{48.f};
			vec2f new_pos{round_to(m_editarea_camera.get_mapped_mousepos().x, f), round_to(m_editarea_camera.get_mapped_mousepos().y, f)};

			if(m_mouse.get_texture())
			{
				auto ptr(m_gameworld.template create_entity<editor_entity>(new_pos));
				ptr->render_object().setTexture(m_mouse.get_texture());
			}
		}

		void on_mouse_right(const vec2f&)
		{
			m_itembar.deselect_all();
			m_mouse.clear();

			auto iter(m_entityhandler.exists_entity_at(m_editarea_camera.get_mapped_mousepos()));
			if(iter != std::end(m_entityhandler))
				m_entityhandler.delete_entity(iter);
		}
	};
}

#endif // RJ_GAME_EDITOR_EDITOR_HPP
<commit_msg>editor: adapted to setting 'editor scroll step'<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GAME_EDITOR_EDITOR_HPP
#define RJ_GAME_EDITOR_EDITOR_HPP

#include "background_editor.hpp"
#include "editor_entity.hpp"
#include "itembar.hpp"
#include "mouse.hpp"
#include <rectojump/game/components/platfrom.hpp>
#include <rectojump/game/camera.hpp>
#include <rectojump/game/world.hpp>

namespace rj
{
	template<typename Game_Handler, typename Game>
	class editor
	{
		Game_Handler& m_gamehandler;
		Game& m_game;
		world& m_gameworld;
		entity_handler& m_entityhandler;

		camera m_editarea_camera;
		camera m_itembar_camera;

		static constexpr float m_itembar_height{100.f};
		editor_mouse m_mouse;
		background_editor<editor> m_background{*this};
		itembar<Game_Handler> m_itembar;

	public:
		editor(Game_Handler& gh) :
			m_gamehandler{gh},
			m_game{gh.get_game()},
			m_gameworld{m_game.get_world()},
			m_entityhandler{m_gameworld.get_entityhandler()},
			m_editarea_camera{m_gamehandler.get_gamewindow()},
			m_itembar_camera{m_gamehandler.get_gamewindow()},
			m_mouse{gh.get_render()},
			m_itembar{gh, {settings::get_window_size<vec2f>().x, m_itembar_height}}
		{this->init();}

		void update(dur duration)
		{
			// edit area
			m_editarea_camera.set_changes();
			m_mouse.update(duration);

			// itembar
			m_itembar_camera.set_changes();
			m_itembar.update(duration);
		}

		void render()
		{
			// edit area
			m_editarea_camera.set_changes();
			m_entityhandler.render();
			m_mouse.render();

			// itembar
			m_itembar_camera.set_changes();
			m_itembar.render();
		}

		void on_activate()
		{
			m_background.reset();
		}

		auto get_gamehandler() noexcept
		-> decltype(m_gamehandler)&
		{return m_gamehandler;}

	private:
		void init()
		{
			m_itembar.on_item_click = [this](base_btn_ptr& b){m_mouse.set_texture(b->get_texture());};

			this->init_input();
			this->init_cameras();
		}

		void init_input()
		{
			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos){this->on_mouse_left(pos);}, btn::Left);

			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos){this->on_mouse_right(pos);}, btn::Right);

			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos)
			{m_editarea_camera.move({settings::get_editor_scroll_step(), 0.f});}, wheel::down);

			m_gamehandler.template add_input<state::editor>(
			[this](const vec2f& pos)
			{
				if(m_editarea_camera.get_center().x >= m_editarea_camera.get_startcenter().x)
					m_editarea_camera.move({-settings::get_editor_scroll_step(), 0.f});
			}, wheel::up);
		}

		void init_cameras() noexcept
		{
			auto window_size(settings::get_window_size<vec2f>());

			float itembar_top{(window_size.y - m_itembar_height) / window_size.y};
			float itembar_height{m_itembar_height / window_size.y};
			float editarea_height{(window_size.y - m_itembar_height) / window_size.y};

			sf::View editarea_view{vec2f{window_size.x, window_size.y - m_itembar_height} / 2.f, {window_size.x, window_size.y - m_itembar_height}};
			editarea_view.setViewport({0.f, 0.f, 1.f ,editarea_height});
			m_editarea_camera.set_view(editarea_view);

			sf::View itembar_view{vec2f{window_size.x, m_itembar_height} / 2.f, {window_size.x, m_itembar_height}};
			itembar_view.setViewport({0.f, itembar_top, 1.f, itembar_height});
			m_itembar_camera.set_view(itembar_view);
		}

		void on_mouse_left(const vec2f&)
		{
			auto mouse_bounds(bounds_from_vec(m_itembar_camera.get_mapped_mousepos()));
			if(mouse_bounds.intersects(m_itembar.get_bounds()))
				return;

			float f{48.f};
			vec2f new_pos{round_to(m_editarea_camera.get_mapped_mousepos().x, f), round_to(m_editarea_camera.get_mapped_mousepos().y, f)};

			if(m_mouse.get_texture())
			{
				auto ptr(m_gameworld.template create_entity<editor_entity>(new_pos));
				ptr->render_object().setTexture(m_mouse.get_texture());
			}
		}

		void on_mouse_right(const vec2f&)
		{
			m_itembar.deselect_all();
			m_mouse.clear();

			auto iter(m_entityhandler.exists_entity_at(m_editarea_camera.get_mapped_mousepos()));
			if(iter != std::end(m_entityhandler))
				m_entityhandler.delete_entity(iter);
		}
	};
}

#endif // RJ_GAME_EDITOR_EDITOR_HPP
<|endoftext|>


<commit_before>/*
 * Copyright 2010-2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "HTMLBodyElementImp.h"

#include <org/w3c/dom/html/Window.h>

namespace org { namespace w3c { namespace dom { namespace bootstrap {

void HTMLBodyElementImp::eval()
{
    HTMLElementImp::eval();
    HTMLElementImp::evalBackground(this);
    HTMLElementImp::evalBgcolor(this);
}

// Node
Node HTMLBodyElementImp::cloneNode(bool deep)
{
    return new(std::nothrow) HTMLBodyElementImp(this, deep);
}

// HTMLBodyElement
html::Function HTMLBodyElementImp::getOnafterprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnblur()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnblur(html::Function onblur)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnerror()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnerror(html::Function onerror)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnfocus()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnfocus(html::Function onfocus)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnhashchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnload(html::Function onload)
{
    getOwnerDocument().getDefaultView().setOnload(onload);
}

html::Function HTMLBodyElementImp::getOnmessage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnmessage(html::Function onmessage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnoffline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnoffline(html::Function onoffline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnonline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnonline(html::Function ononline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpopstate()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpagehide()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpageshow()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnredo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnredo(html::Function onredo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnresize()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnresize(html::Function onresize)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnstorage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnstorage(html::Function onstorage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnundo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnundo(html::Function onundo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnunload(html::Function onunload)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getText()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setText(std::u16string text)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBgColor()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBgColor(std::u16string bgColor)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBackground()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBackground(std::u16string background)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setLink(std::u16string link)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getVLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setVLink(std::u16string vLink)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getALink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setALink(std::u16string aLink)
{
    // TODO: implement me!
}

}}}}  // org::w3c::dom::bootstrap
<commit_msg>(HTMLBodyElementImp::eval) : Evaluate text attribute.<commit_after>/*
 * Copyright 2010-2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "HTMLBodyElementImp.h"

#include <org/w3c/dom/html/Window.h>

namespace org { namespace w3c { namespace dom { namespace bootstrap {

void HTMLBodyElementImp::eval()
{
    HTMLElementImp::eval();
    HTMLElementImp::evalBackground(this);
    HTMLElementImp::evalBgcolor(this);
    HTMLElementImp::evalColor(this, u"text", u"color");
}

// Node
Node HTMLBodyElementImp::cloneNode(bool deep)
{
    return new(std::nothrow) HTMLBodyElementImp(this, deep);
}

// HTMLBodyElement
html::Function HTMLBodyElementImp::getOnafterprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnafterprint(html::Function onafterprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeprint()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeprint(html::Function onbeforeprint)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnbeforeunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnbeforeunload(html::Function onbeforeunload)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnblur()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnblur(html::Function onblur)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnerror()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnerror(html::Function onerror)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnfocus()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnfocus(html::Function onfocus)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnhashchange()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnhashchange(html::Function onhashchange)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnload(html::Function onload)
{
    getOwnerDocument().getDefaultView().setOnload(onload);
}

html::Function HTMLBodyElementImp::getOnmessage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnmessage(html::Function onmessage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnoffline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnoffline(html::Function onoffline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnonline()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnonline(html::Function ononline)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpopstate()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpopstate(html::Function onpopstate)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpagehide()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpagehide(html::Function onpagehide)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnpageshow()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnpageshow(html::Function onpageshow)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnredo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnredo(html::Function onredo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnresize()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnresize(html::Function onresize)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnstorage()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnstorage(html::Function onstorage)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnundo()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnundo(html::Function onundo)
{
    // TODO: implement me!
}

html::Function HTMLBodyElementImp::getOnunload()
{
    // TODO: implement me!
    return static_cast<Object*>(0);
}

void HTMLBodyElementImp::setOnunload(html::Function onunload)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getText()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setText(std::u16string text)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBgColor()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBgColor(std::u16string bgColor)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getBackground()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setBackground(std::u16string background)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setLink(std::u16string link)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getVLink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setVLink(std::u16string vLink)
{
    // TODO: implement me!
}

std::u16string HTMLBodyElementImp::getALink()
{
    // TODO: implement me!
    return u"";
}

void HTMLBodyElementImp::setALink(std::u16string aLink)
{
    // TODO: implement me!
}

}}}}  // org::w3c::dom::bootstrap
<|endoftext|>


<commit_before>// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <sys/mman.h>

#include <map>

#include "gtest/gtest.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "test/util/fs_util.h"
#include "test/util/posix_error.h"
#include "test/util/test_util.h"

namespace gvisor {
namespace testing {
namespace {

using ::absl::StrFormat;

// AnonUsageFromMeminfo scrapes the current anonymous memory usage from
// /proc/meminfo and returns it in bytes.
PosixErrorOr<uint64_t> AnonUsageFromMeminfo() {
  ASSIGN_OR_RETURN_ERRNO(auto meminfo, GetContents("/proc/meminfo"));
  std::vector<std::string> lines(absl::StrSplit(meminfo, '\n'));

  // Try to find AnonPages line, the format is AnonPages:\\s+(\\d+) kB\n.
  for (const auto& line : lines) {
    if (!absl::StartsWith(line, "AnonPages:")) {
      continue;
    }

    std::vector<std::string> parts(
        absl::StrSplit(line, ' ', absl::SkipEmpty()));
    if (parts.size() == 3) {
      // The size is the second field, let's try to parse it as a number.
      ASSIGN_OR_RETURN_ERRNO(auto anon_kb, Atoi<uint64_t>(parts[1]));
      return anon_kb * 1024;
    }

    return PosixError(EINVAL, "AnonPages field in /proc/meminfo was malformed");
  }

  return PosixError(EINVAL, "AnonPages field not found in /proc/meminfo");
}

TEST(MemoryAccounting, AnonAccountingPreservedOnSaveRestore) {
  // This test isn't meaningful on Linux. /proc/meminfo reports system-wide
  // memory usage, which can change arbitrarily in Linux from other activity on
  // the machine. In gvisor, this test is the only thing running on the
  // "machine", so values in /proc/meminfo accurately reflect the memory used by
  // the test.
  SKIP_IF(!IsRunningOnGvisor());

  uint64_t anon_initial = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());

  // Cause some anonymous memory usage.
  uint64_t map_bytes = Megabytes(512);
  char* mem =
      static_cast<char*>(mmap(nullptr, map_bytes, PROT_READ | PROT_WRITE,
                              MAP_POPULATE | MAP_ANON | MAP_PRIVATE, -1, 0));
  ASSERT_NE(mem, MAP_FAILED)
      << "Map failed, errno: " << errno << " (" << strerror(errno) << ").";

  // Write something to each page to prevent them from being decommited on
  // S/R. Zero pages are dropped on save.
  for (uint64_t i = 0; i < map_bytes; i += kPageSize) {
    mem[i] = 'a';
  }

  uint64_t anon_after_alloc = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());
  EXPECT_THAT(anon_after_alloc,
              EquivalentWithin(anon_initial + map_bytes, 0.03));

  // We have many implicit S/R cycles from scraping /proc/meminfo throughout the
  // test, but throw an explicit S/R in here as well.
  MaybeSave();

  // Usage should remain the same across S/R.
  uint64_t anon_after_sr = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());
  EXPECT_THAT(anon_after_sr, EquivalentWithin(anon_after_alloc, 0.03));
}

}  // namespace
}  // namespace testing
}  // namespace gvisor
<commit_msg>Increase error margin for memory accounting test.<commit_after>// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <sys/mman.h>

#include <map>

#include "gtest/gtest.h"
#include "absl/strings/match.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_split.h"
#include "test/util/fs_util.h"
#include "test/util/posix_error.h"
#include "test/util/test_util.h"

namespace gvisor {
namespace testing {
namespace {

using ::absl::StrFormat;

// AnonUsageFromMeminfo scrapes the current anonymous memory usage from
// /proc/meminfo and returns it in bytes.
PosixErrorOr<uint64_t> AnonUsageFromMeminfo() {
  ASSIGN_OR_RETURN_ERRNO(auto meminfo, GetContents("/proc/meminfo"));
  std::vector<std::string> lines(absl::StrSplit(meminfo, '\n'));

  // Try to find AnonPages line, the format is AnonPages:\\s+(\\d+) kB\n.
  for (const auto& line : lines) {
    if (!absl::StartsWith(line, "AnonPages:")) {
      continue;
    }

    std::vector<std::string> parts(
        absl::StrSplit(line, ' ', absl::SkipEmpty()));
    if (parts.size() == 3) {
      // The size is the second field, let's try to parse it as a number.
      ASSIGN_OR_RETURN_ERRNO(auto anon_kb, Atoi<uint64_t>(parts[1]));
      return anon_kb * 1024;
    }

    return PosixError(EINVAL, "AnonPages field in /proc/meminfo was malformed");
  }

  return PosixError(EINVAL, "AnonPages field not found in /proc/meminfo");
}

TEST(MemoryAccounting, AnonAccountingPreservedOnSaveRestore) {
  // This test isn't meaningful on Linux. /proc/meminfo reports system-wide
  // memory usage, which can change arbitrarily in Linux from other activity on
  // the machine. In gvisor, this test is the only thing running on the
  // "machine", so values in /proc/meminfo accurately reflect the memory used by
  // the test.
  SKIP_IF(!IsRunningOnGvisor());

  uint64_t anon_initial = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());

  // Cause some anonymous memory usage.
  uint64_t map_bytes = Megabytes(512);
  char* mem =
      static_cast<char*>(mmap(nullptr, map_bytes, PROT_READ | PROT_WRITE,
                              MAP_POPULATE | MAP_ANON | MAP_PRIVATE, -1, 0));
  ASSERT_NE(mem, MAP_FAILED)
      << "Map failed, errno: " << errno << " (" << strerror(errno) << ").";

  // Write something to each page to prevent them from being decommited on
  // S/R. Zero pages are dropped on save.
  for (uint64_t i = 0; i < map_bytes; i += kPageSize) {
    mem[i] = 'a';
  }

  uint64_t anon_after_alloc = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());
  EXPECT_THAT(anon_after_alloc,
              EquivalentWithin(anon_initial + map_bytes, 0.04));

  // We have many implicit S/R cycles from scraping /proc/meminfo throughout the
  // test, but throw an explicit S/R in here as well.
  MaybeSave();

  // Usage should remain the same across S/R.
  uint64_t anon_after_sr = ASSERT_NO_ERRNO_AND_VALUE(AnonUsageFromMeminfo());
  EXPECT_THAT(anon_after_sr, EquivalentWithin(anon_after_alloc, 0.04));
}

}  // namespace
}  // namespace testing
}  // namespace gvisor
<|endoftext|>


<commit_before>#include "libtest.h"

using namespace std;
#include "../lib/json/json.h"

void test_empty_dict(){

    string message = "{}";

    JsonValue * value = JsonValue::fromString(message);

    ASSERT_NOT_NULL(value, "Parsing null");

    JsonDict* dict_p = JDICT(value);
    ASSERT_NOT_NULL(dict_p, "Dict null");

    ASSERT(dict_p->size() == 0, "Dict not null");
}

void test_dict_one_val(){
    string fix[] = {
        "{\"a\":\"b\"}",
        "{\"a\" :\"b\"}",
        "{\"a\": \"b\"}",
        "{\"a\" : \"b\"}",
        "{  \"a\"  :  \"b\"  }"
    };

    for(int i=0; i < 5; i++){
        string message = fix[i];

        JsonValue * value = JsonValue::fromString(message);

        ASSERT_NOT_NULL(value, "Parsing null");

        JsonDict* dict_p = JDICT(value);
        ASSERT_NOT_NULL(dict_p, "Dict null");

        ASSERT(dict_p->size() == 1, "Dict not null");
        ASSERT_EQUAL((string) *JSTRING((*dict_p)["a"]), "b", "d[a]!=b");
    }
}

void test_empty_list(){
    string message = "[]";

    JsonValue * value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing null");

    JsonList * list_p = JLIST(value);
    ASSERT_NOT_NULL(list_p, "List null");

    ASSERT(list_p->size() == 0, "List not empty");
}

void test_empty_string(){
    string message = "\"\"";

    JsonValue * value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonString* string_p = JSTRING(value);
    ASSERT_NOT_NULL(string_p, "String not null");

    ASSERT_EQUAL((string) *string_p, "", "Empty string");
}

void test_true_bool(){
    string message = "true";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonBool * bool_p = JBOOL(value);
    ASSERT_NOT_NULL(bool_p, "Cast");

    ASSERT(*bool_p, "Must be true");
}

void test_false_bool(){
    string message = "false";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonBool * bool_p = JBOOL(value);
    ASSERT_NOT_NULL(bool_p, "Cast");

    ASSERT_FALSE(*bool_p, "Must be false");
}

void test_null(){
    string message = "null";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonNull* null_p = JNULL(value);
    ASSERT_NOT_NULL(null_p, "Cast to null");

    ASSERT_NULL(*null_p, "Is null");

}

#define TESTVEC {T(test_empty_dict), T(test_empty_list), T(test_empty_string), T(test_true_bool), T(test_false_bool), T(test_null), T(test_dict_one_val)}
TEST();
<commit_msg>[code/test] Added test for list containing different value types.<commit_after>#include "libtest.h"

using namespace std;
#include "../lib/json/json.h"

void test_empty_dict(){

    string message = "{}";

    JsonValue * value = JsonValue::fromString(message);

    ASSERT_NOT_NULL(value, "Parsing null");

    JsonDict* dict_p = JDICT(value);
    ASSERT_NOT_NULL(dict_p, "Dict null");

    ASSERT(dict_p->size() == 0, "Dict not null");
}

void test_dict_one_val(){
    string fix[] = {
        "{\"a\":\"b\"}",
        "{\"a\" :\"b\"}",
        "{\"a\": \"b\"}",
        "{\"a\" : \"b\"}",
        "{  \"a\"  :  \"b\"  }"
    };

    for(int i=0; i < 5; i++){
        string message = fix[i];

        JsonValue * value = JsonValue::fromString(message);

        ASSERT_NOT_NULL(value, "Parsing null");

        JsonDict* dict_p = JDICT(value);
        ASSERT_NOT_NULL(dict_p, "Dict null");

        ASSERT(dict_p->size() == 1, "Dict not null");
        ASSERT_EQUAL((string) *JSTRING((*dict_p)["a"]), "b", "d[a]!=b");
    }
}

void test_empty_list(){
    string message = "[]";

    JsonValue * value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing null");

    JsonList * list_p = JLIST(value);
    ASSERT_NOT_NULL(list_p, "List null");

    ASSERT(list_p->size() == 0, "List not empty");
}

void test_empty_string(){
    string message = "\"\"";

    JsonValue * value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonString* string_p = JSTRING(value);
    ASSERT_NOT_NULL(string_p, "String not null");

    ASSERT_EQUAL((string) *string_p, "", "Empty string");
}

void test_true_bool(){
    string message = "true";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonBool * bool_p = JBOOL(value);
    ASSERT_NOT_NULL(bool_p, "Cast");

    ASSERT(*bool_p, "Must be true");
}

void test_false_bool(){
    string message = "false";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonBool * bool_p = JBOOL(value);
    ASSERT_NOT_NULL(bool_p, "Cast");

    ASSERT_FALSE(*bool_p, "Must be false");
}

void test_null(){
    string message = "null";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonNull* null_p = JNULL(value);
    ASSERT_NOT_NULL(null_p, "Cast to null");

    ASSERT_NULL(*null_p, "Is null");

}

void test_list_of_multiple_elemets(){
    string message ="[ true, false, null, \"plop\",1,2 , 3]";

    JsonValue* value = JsonValue::fromString(message);
    ASSERT_NOT_NULL(value, "Parsing not null");

    JsonList* list_p = JLIST(value);
    ASSERT_NOT_NULL(list_p, "Cast");

    ASSERT_EQUAL(list_p->size(), 7, "List contain 7 elements");
}

#define TESTVEC {T(test_empty_dict), T(test_empty_list), T(test_empty_string), T(test_true_bool), T(test_false_bool), T(test_null), T(test_dict_one_val), T(test_list_of_multiple_elemets)}
TEST();
<|endoftext|>