<commit_before>/*

Copyright (c) 2003, 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_STAT_HPP_INCLUDED
#define TORRENT_STAT_HPP_INCLUDED

#include <algorithm>
#include <vector>
#include <assert.h>
#include <cstring>

#include "libtorrent/size_type.hpp"
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

namespace libtorrent
{
	class TORRENT_EXPORT stat_channel
	{
	friend class invariant_access;
	public:
		enum { history = 10 };

		stat_channel()
			: m_counter(0)
			, m_total_counter(0)
			, m_rate_sum(0)
		{
			std::memset(m_rate_history, 0, sizeof(m_rate_history));
		}

		void operator+=(stat_channel const& s)
		{
			m_counter += s.m_counter;
			m_total_counter += s.m_counter;
		}

		void add(int count)
		{
			TORRENT_ASSERT(count >= 0);

			m_counter += count;
			m_total_counter += count;
		}

		// should be called once every second
		void second_tick(float tick_interval);
		float rate() const { return m_rate_sum / float(history); }
		size_type rate_sum() const { return m_rate_sum; }
		size_type total() const { return m_total_counter; }

		void offset(size_type counter)
		{
			TORRENT_ASSERT(counter >= 0);
			m_total_counter += counter;
		}

		size_type counter() const { return m_counter; }

	private:

#ifndef NDEBUG
		void check_invariant() const
		{
			int sum = 0;
			for (int i = 0; i < history; ++i) sum += m_rate_history[i];
			TORRENT_ASSERT(m_rate_sum == sum);
			TORRENT_ASSERT(m_total_counter >= 0);
		}
#endif

		// history of rates a few seconds back
		int m_rate_history[history];

		// the accumulator for this second.
		int m_counter;

		// total counters
		size_type m_total_counter;

		// sum of all elements in m_rate_history
		size_type m_rate_sum;
	};

	class TORRENT_EXPORT stat
	{
	friend class invariant_access;
	public:
		void operator+=(const stat& s)
		{
			for (int i = 0; i < num_channels; ++i)
				m_stat[i] += s.m_stat[i];
		}

		void received_bytes(int bytes_payload, int bytes_protocol)
		{
			TORRENT_ASSERT(bytes_payload >= 0);
			TORRENT_ASSERT(bytes_protocol >= 0);

			m_stat[download_payload].add(bytes_payload);
			m_stat[download_protocol].add(bytes_protocol);
		}

		void sent_bytes(int bytes_payload, int bytes_protocol)
		{
			TORRENT_ASSERT(bytes_payload >= 0);
			TORRENT_ASSERT(bytes_protocol >= 0);

			m_stat[upload_payload].add(bytes_payload);
			m_stat[upload_protocol].add(bytes_protocol);
		}

		// calculate ip protocol overhead
		void calc_ip_overhead()
		{
			int uploaded = m_stat[upload_protocol].counter()
				+ m_stat[upload_payload].counter();
			int downloaded = m_stat[download_protocol].counter()
				+ m_stat[download_payload].counter();

			// IP + TCP headers are 40 bytes per MTU (1460)
			// bytes of payload, but at least 40 bytes
			m_stat[upload_ip_protocol].add((std::max)(uploaded / 1460, 40));
			m_stat[download_ip_protocol].add((std::max)(downloaded / 1460, 40));

			// also account for ACK traffic. That adds to the transfers
			// in the opposite direction. Even on connections with symmetric
			// transfer rates, it seems to add a penalty.
			m_stat[upload_ip_protocol].add((std::max)(downloaded / 20, 40));
			m_stat[download_ip_protocol].add((std::max)(uploaded / 20, 40));
		}

		int upload_ip_overhead() const { return m_stat[upload_ip_protocol].counter(); }
		int download_ip_overhead() const { return m_stat[download_ip_protocol].counter(); }

		// should be called once every second
		void second_tick(float tick_interval)
		{
			for (int i = 0; i < num_channels; ++i)
				m_stat[i].second_tick(tick_interval);
		}

		float upload_rate() const
		{
			return (m_stat[upload_payload].rate_sum()
				+ m_stat[upload_protocol].rate_sum()
				+ m_stat[upload_ip_protocol].rate_sum())
				/ float(stat_channel::history);
		}

		float download_rate() const
		{
			return (m_stat[download_payload].rate_sum()
				+ m_stat[download_protocol].rate_sum()
				+ m_stat[download_ip_protocol].rate_sum())
				/ float(stat_channel::history);
		}

		float upload_payload_rate() const
		{ return m_stat[upload_payload].rate(); }

		float download_payload_rate() const
		{ return m_stat[download_payload].rate(); }

		size_type total_payload_upload() const
		{ return m_stat[upload_payload].total(); }
		size_type total_payload_download() const
		{ return m_stat[download_payload].total(); }

		size_type total_protocol_upload() const
		{ return m_stat[upload_protocol].total(); }
		size_type total_protocol_download() const
		{ return m_stat[download_protocol].total(); }

		// this is used to offset the statistics when a
		// peer_connection is opened and have some previous
		// transfers from earlier connections.
		void add_stat(size_type downloaded, size_type uploaded)
		{
			TORRENT_ASSERT(downloaded >= 0);
			TORRENT_ASSERT(uploaded >= 0);
			m_stat[download_payload].offset(downloaded);
			m_stat[upload_payload].offset(uploaded);
		}

		size_type last_payload_downloaded() const
		{ return m_stat[download_payload].counter(); }
		size_type last_payload_uploaded() const
		{ return m_stat[upload_payload].counter(); }

	private:

		// these are the channels we keep stats for
		enum
		{
			upload_payload,
			upload_protocol,
			upload_ip_protocol,
			download_payload,
			download_protocol,
			download_ip_protocol,
			num_channels
		};

		stat_channel m_stat[num_channels];
	};

}

#endif // TORRENT_STAT_HPP_INCLUDED

<commit_msg>updated IP overhead calculation<commit_after>/*

Copyright (c) 2003, 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_STAT_HPP_INCLUDED
#define TORRENT_STAT_HPP_INCLUDED

#include <algorithm>
#include <vector>
#include <assert.h>
#include <cstring>

#include "libtorrent/size_type.hpp"
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

namespace libtorrent
{
	class TORRENT_EXPORT stat_channel
	{
	friend class invariant_access;
	public:
		enum { history = 10 };

		stat_channel()
			: m_counter(0)
			, m_total_counter(0)
			, m_rate_sum(0)
		{
			std::memset(m_rate_history, 0, sizeof(m_rate_history));
		}

		void operator+=(stat_channel const& s)
		{
			m_counter += s.m_counter;
			m_total_counter += s.m_counter;
		}

		void add(int count)
		{
			TORRENT_ASSERT(count >= 0);

			m_counter += count;
			m_total_counter += count;
		}

		// should be called once every second
		void second_tick(float tick_interval);
		float rate() const { return m_rate_sum / float(history); }
		size_type rate_sum() const { return m_rate_sum; }
		size_type total() const { return m_total_counter; }

		void offset(size_type counter)
		{
			TORRENT_ASSERT(counter >= 0);
			m_total_counter += counter;
		}

		size_type counter() const { return m_counter; }

	private:

#ifndef NDEBUG
		void check_invariant() const
		{
			int sum = 0;
			for (int i = 0; i < history; ++i) sum += m_rate_history[i];
			TORRENT_ASSERT(m_rate_sum == sum);
			TORRENT_ASSERT(m_total_counter >= 0);
		}
#endif

		// history of rates a few seconds back
		int m_rate_history[history];

		// the accumulator for this second.
		int m_counter;

		// total counters
		size_type m_total_counter;

		// sum of all elements in m_rate_history
		size_type m_rate_sum;
	};

	class TORRENT_EXPORT stat
	{
	friend class invariant_access;
	public:
		void operator+=(const stat& s)
		{
			for (int i = 0; i < num_channels; ++i)
				m_stat[i] += s.m_stat[i];
		}

		void received_bytes(int bytes_payload, int bytes_protocol)
		{
			TORRENT_ASSERT(bytes_payload >= 0);
			TORRENT_ASSERT(bytes_protocol >= 0);

			m_stat[download_payload].add(bytes_payload);
			m_stat[download_protocol].add(bytes_protocol);
		}

		void sent_bytes(int bytes_payload, int bytes_protocol)
		{
			TORRENT_ASSERT(bytes_payload >= 0);
			TORRENT_ASSERT(bytes_protocol >= 0);

			m_stat[upload_payload].add(bytes_payload);
			m_stat[upload_protocol].add(bytes_protocol);
		}

		// calculate ip protocol overhead
		void calc_ip_overhead()
		{
			int uploaded = m_stat[upload_protocol].counter()
				+ m_stat[upload_payload].counter();
			int downloaded = m_stat[download_protocol].counter()
				+ m_stat[download_payload].counter();

			// IP + TCP headers are 40 bytes per MTU (1460)
			// bytes of payload, but at least 40 bytes
			m_stat[upload_ip_protocol].add((std::max)(uploaded / 1460, uploaded>0?40:0));
			m_stat[download_ip_protocol].add((std::max)(downloaded / 1460, downloaded>0?40:0));

			// also account for ACK traffic. That adds to the transfers
			// in the opposite direction. Even on connections with symmetric
			// transfer rates, it seems to add a penalty.
			m_stat[upload_ip_protocol].add((std::max)(downloaded * 40 / 1460, downloaded>0?40:0));
			m_stat[download_ip_protocol].add((std::max)(uploaded * 40 / 1460, uploaded>0?40:0));
		}

		int upload_ip_overhead() const { return m_stat[upload_ip_protocol].counter(); }
		int download_ip_overhead() const { return m_stat[download_ip_protocol].counter(); }

		// should be called once every second
		void second_tick(float tick_interval)
		{
			for (int i = 0; i < num_channels; ++i)
				m_stat[i].second_tick(tick_interval);
		}

		float upload_rate() const
		{
			return (m_stat[upload_payload].rate_sum()
				+ m_stat[upload_protocol].rate_sum()
				+ m_stat[upload_ip_protocol].rate_sum())
				/ float(stat_channel::history);
		}

		float download_rate() const
		{
			return (m_stat[download_payload].rate_sum()
				+ m_stat[download_protocol].rate_sum()
				+ m_stat[download_ip_protocol].rate_sum())
				/ float(stat_channel::history);
		}

		float upload_payload_rate() const
		{ return m_stat[upload_payload].rate(); }

		float download_payload_rate() const
		{ return m_stat[download_payload].rate(); }

		size_type total_payload_upload() const
		{ return m_stat[upload_payload].total(); }
		size_type total_payload_download() const
		{ return m_stat[download_payload].total(); }

		size_type total_protocol_upload() const
		{ return m_stat[upload_protocol].total(); }
		size_type total_protocol_download() const
		{ return m_stat[download_protocol].total(); }

		// this is used to offset the statistics when a
		// peer_connection is opened and have some previous
		// transfers from earlier connections.
		void add_stat(size_type downloaded, size_type uploaded)
		{
			TORRENT_ASSERT(downloaded >= 0);
			TORRENT_ASSERT(uploaded >= 0);
			m_stat[download_payload].offset(downloaded);
			m_stat[upload_payload].offset(uploaded);
		}

		size_type last_payload_downloaded() const
		{ return m_stat[download_payload].counter(); }
		size_type last_payload_uploaded() const
		{ return m_stat[upload_payload].counter(); }

	private:

		// these are the channels we keep stats for
		enum
		{
			upload_payload,
			upload_protocol,
			upload_ip_protocol,
			download_payload,
			download_protocol,
			download_ip_protocol,
			num_channels
		};

		stat_channel m_stat[num_channels];
	};

}

#endif // TORRENT_STAT_HPP_INCLUDED

<|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_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED

#if (!defined (__MACH__) && !defined (_WIN32)) || defined (TORRENT_USE_BOOST_DATE_TIME)

#include <boost/date_time/posix_time/posix_time.hpp>

namespace libtorrent
{
	typedef boost::posix_time::ptime ptime;
	typedef boost::posix_time::time_duration time_duration;
	inline ptime time_now()
	{ return boost::posix_time::microsec_clock::universal_time(); }
	inline ptime min_time()
	{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
	inline ptime max_time()
	{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
	inline time_duration seconds(int s) { return boost::posix_time::seconds(s); }
	inline time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
	inline time_duration microsec(int s) { return boost::posix_time::microsec(s); }
	inline time_duration minutes(int s) { return boost::posix_time::minutes(s); }
	inline time_duration hours(int s) { return boost::posix_time::hours(s); }

	inline int total_seconds(time_duration td)
	{ return td.total_seconds(); }
	inline int total_milliseconds(time_duration td)
	{ return td.total_milliseconds(); }
	inline boost::int64_t total_microseconds(time_duration td)
	{ return td.total_microseconds(); }

}

#else

#include <asio/time_traits.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>

namespace libtorrent
{
	// libtorrent time_duration type
	struct time_duration
	{
		time_duration() {}
		explicit time_duration(boost::int64_t d) : diff(d) {}
		boost::int64_t diff;
	};

	inline bool is_negative(time_duration dt) { return dt.diff < 0; }
	inline bool operator<(time_duration lhs, time_duration rhs)
	{ return lhs.diff < rhs.diff; }
	inline bool operator>(time_duration lhs, time_duration rhs)
	{ return lhs.diff > rhs.diff; }

	// libtorrent time type
	struct ptime
	{
		ptime() {}
		explicit ptime(boost::int64_t t): time(t) {}
		boost::int64_t time;
	};

	inline bool operator>(ptime lhs, ptime rhs)
	{ return lhs.time > rhs.time; }
	inline bool operator>=(ptime lhs, ptime rhs)
	{ return lhs.time >= rhs.time; }
	inline bool operator<=(ptime lhs, ptime rhs)
	{ return lhs.time <= rhs.time; }
	inline bool operator<(ptime lhs, ptime rhs)
	{ return lhs.time < rhs.time; }
	inline bool operator!=(ptime lhs, ptime rhs)
	{ return lhs.time != rhs.time;}
	inline bool operator==(ptime lhs, ptime rhs)
	{ return lhs.time == rhs.time;}
	inline time_duration operator-(ptime lhs, ptime rhs)
	{ return time_duration(lhs.time - rhs.time); }
	inline ptime operator+(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time + rhs.diff); }
	inline ptime operator+(time_duration lhs, ptime rhs)
	{ return ptime(rhs.time + lhs.diff); }
	inline ptime operator-(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time - rhs.diff); }

	ptime time_now();
	inline ptime min_time() { return ptime(0); }
	inline ptime max_time() { return ptime((std::numeric_limits<boost::int64_t>::max)()); }
	int total_seconds(time_duration td);
	int total_milliseconds(time_duration td);
	boost::int64_t total_microseconds(time_duration td);
}

// asio time_traits
namespace asio
{
	template<>
	struct time_traits<libtorrent::ptime>
	{
		typedef libtorrent::ptime time_type;
		typedef libtorrent::time_duration duration_type;
		static time_type now()
		{ return time_type(libtorrent::time_now()); }
		static time_type add(time_type t, duration_type d)
		{ return time_type(t.time + d.diff);}
		static duration_type subtract(time_type t1, time_type t2)
		{ return duration_type(t1 - t2); }
		static bool less_than(time_type t1, time_type t2)
		{ return t1 < t2; }
		static boost::posix_time::time_duration to_posix_duration(
			duration_type d)
		{ return boost::posix_time::microseconds(libtorrent::total_microseconds(d)); }
	};
}

#if defined(__MACH__)

#include <mach/mach_time.h>
#include <boost/cstdint.hpp>

// high precision timer for darwin intel and ppc

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t absolutetime_to_microseconds(boost::int64_t at)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
				mach_timebase_info(&timebase_info);
			// make sure we don't overflow
			assert((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
				|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
			return at / 1000 * timebase_info.numer / timebase_info.denom;
		}

		inline boost::int64_t microseconds_to_absolutetime(boost::int64_t ms)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
			{
				mach_timebase_info(&timebase_info);
				assert(timebase_info.numer > 0);
				assert(timebase_info.denom > 0);
			}
			// make sure we don't overflow
			assert((ms >= 0 && ms <= ms * timebase_info.denom / timebase_info.numer * 1000)
				|| (ms < 0 && ms > ms * timebase_info.denom / timebase_info.numer * 1000));
			return ms * timebase_info.denom / timebase_info.numer * 1000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff);
	}

	inline ptime time_now() { return ptime(mach_absolute_time()); }

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60 * 60));
	}

}
#elif defined(_WIN32)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);

			return pc * 1000000 / performace_counter_frequency.QuadPart;
		}

		inline boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);
			return ms * performace_counter_frequency.QuadPart / 1000000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff);
	}

	inline ptime time_now()
	{
		LARGE_INTEGER now;
		QueryPerformanceCounter(&now);
		return ptime(now.QuadPart);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60 * 60));
	}

}

#endif

#endif
#endif

<commit_msg>added support for posix timer clock_gettime()<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_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED

#ifndef _WIN32
#include <unistd.h>
#endif

#if (!defined (__MACH__) && !defined (_WIN32) && !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0) || defined (TORRENT_USE_BOOST_DATE_TIME)

#include <boost/date_time/posix_time/posix_time.hpp>

namespace libtorrent
{
	typedef boost::posix_time::ptime ptime;
	typedef boost::posix_time::time_duration time_duration;
	inline ptime time_now()
	{ return boost::posix_time::microsec_clock::universal_time(); }
	inline ptime min_time()
	{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
	inline ptime max_time()
	{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
	inline time_duration seconds(int s) { return boost::posix_time::seconds(s); }
	inline time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
	inline time_duration microsec(int s) { return boost::posix_time::microsec(s); }
	inline time_duration minutes(int s) { return boost::posix_time::minutes(s); }
	inline time_duration hours(int s) { return boost::posix_time::hours(s); }

	inline int total_seconds(time_duration td)
	{ return td.total_seconds(); }
	inline int total_milliseconds(time_duration td)
	{ return td.total_milliseconds(); }
	inline boost::int64_t total_microseconds(time_duration td)
	{ return td.total_microseconds(); }

}

#else

#include <asio/time_traits.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>

namespace libtorrent
{
	// libtorrent time_duration type
	struct time_duration
	{
		time_duration() {}
		explicit time_duration(boost::int64_t d) : diff(d) {}
		boost::int64_t diff;
	};

	inline bool is_negative(time_duration dt) { return dt.diff < 0; }
	inline bool operator<(time_duration lhs, time_duration rhs)
	{ return lhs.diff < rhs.diff; }
	inline bool operator>(time_duration lhs, time_duration rhs)
	{ return lhs.diff > rhs.diff; }

	// libtorrent time type
	struct ptime
	{
		ptime() {}
		explicit ptime(boost::int64_t t): time(t) {}
		boost::int64_t time;
	};

	inline bool operator>(ptime lhs, ptime rhs)
	{ return lhs.time > rhs.time; }
	inline bool operator>=(ptime lhs, ptime rhs)
	{ return lhs.time >= rhs.time; }
	inline bool operator<=(ptime lhs, ptime rhs)
	{ return lhs.time <= rhs.time; }
	inline bool operator<(ptime lhs, ptime rhs)
	{ return lhs.time < rhs.time; }
	inline bool operator!=(ptime lhs, ptime rhs)
	{ return lhs.time != rhs.time;}
	inline bool operator==(ptime lhs, ptime rhs)
	{ return lhs.time == rhs.time;}
	inline time_duration operator-(ptime lhs, ptime rhs)
	{ return time_duration(lhs.time - rhs.time); }
	inline ptime operator+(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time + rhs.diff); }
	inline ptime operator+(time_duration lhs, ptime rhs)
	{ return ptime(rhs.time + lhs.diff); }
	inline ptime operator-(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time - rhs.diff); }

	ptime time_now();
	inline ptime min_time() { return ptime(0); }
	inline ptime max_time() { return ptime((std::numeric_limits<boost::int64_t>::max)()); }
	int total_seconds(time_duration td);
	int total_milliseconds(time_duration td);
	boost::int64_t total_microseconds(time_duration td);
}

// asio time_traits
namespace asio
{
	template<>
	struct time_traits<libtorrent::ptime>
	{
		typedef libtorrent::ptime time_type;
		typedef libtorrent::time_duration duration_type;
		static time_type now()
		{ return time_type(libtorrent::time_now()); }
		static time_type add(time_type t, duration_type d)
		{ return time_type(t.time + d.diff);}
		static duration_type subtract(time_type t1, time_type t2)
		{ return duration_type(t1 - t2); }
		static bool less_than(time_type t1, time_type t2)
		{ return t1 < t2; }
		static boost::posix_time::time_duration to_posix_duration(
			duration_type d)
		{ return boost::posix_time::microseconds(libtorrent::total_microseconds(d)); }
	};
}

#if defined(__MACH__)

#include <mach/mach_time.h>
#include <boost/cstdint.hpp>

// high precision timer for darwin intel and ppc

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t absolutetime_to_microseconds(boost::int64_t at)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
				mach_timebase_info(&timebase_info);
			// make sure we don't overflow
			assert((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
				|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
			return at / 1000 * timebase_info.numer / timebase_info.denom;
		}

		inline boost::int64_t microseconds_to_absolutetime(boost::int64_t ms)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
			{
				mach_timebase_info(&timebase_info);
				assert(timebase_info.numer > 0);
				assert(timebase_info.denom > 0);
			}
			// make sure we don't overflow
			assert((ms >= 0 && ms <= ms * timebase_info.denom / timebase_info.numer * 1000)
				|| (ms < 0 && ms > ms * timebase_info.denom / timebase_info.numer * 1000));
			return ms * timebase_info.denom / timebase_info.numer * 1000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff);
	}

	inline ptime time_now() { return ptime(mach_absolute_time()); }

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60 * 60));
	}

}
#elif defined(_WIN32)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);

			return pc * 1000000 / performace_counter_frequency.QuadPart;
		}

		inline boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);
			return ms * performace_counter_frequency.QuadPart / 1000000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff);
	}

	inline ptime time_now()
	{
		LARGE_INTEGER now;
		QueryPerformanceCounter(&now);
		return ptime(now.QuadPart);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60 * 60));
	}

}

#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0

#include <time.h>

namespace libtorrent
{
	inline int total_seconds(time_duration td)
	{
		return td.diff / 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return td.diff / 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return td.diff;
	}

	inline ptime time_now()
	{
		timespec ts;
		clock_gettime(CLOCK_MONOTONIC, &ts);
		return ptime(boost::int64_t(ts.tv_sec) + ts.nsec / 1000);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(s);
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(s * 1000);
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(s * 1000000);
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(s * 1000000 * 60);
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(s * 1000000 * 60 * 60);
	}

}

#endif

#endif
#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_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED

#include <ctime>

#ifndef _WIN32
#include <unistd.h>
#endif

namespace libtorrent
{
	inline char const* time_now_string()
	{
		time_t t = std::time(0);
		tm* timeinfo = std::localtime(&t);
		static char str[200];
		std::strftime(str, 200, "%b %d %X", timeinfo);
		return str;
	}
}

#if (!defined (__MACH__) && !defined (_WIN32) && !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0) || defined (TORRENT_USE_BOOST_DATE_TIME)

#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace libtorrent
{
	typedef boost::posix_time::ptime ptime;
	typedef boost::posix_time::time_duration time_duration;
	inline ptime time_now()
	{ return boost::posix_time::microsec_clock::universal_time(); }
	inline ptime min_time()
	{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
	inline ptime max_time()
	{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
	inline time_duration seconds(int s) { return boost::posix_time::seconds(s); }
	inline time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
	inline time_duration microsec(int s) { return boost::posix_time::microsec(s); }
	inline time_duration minutes(int s) { return boost::posix_time::minutes(s); }
	inline time_duration hours(int s) { return boost::posix_time::hours(s); }

	inline int total_seconds(time_duration td)
	{ return td.total_seconds(); }
	inline int total_milliseconds(time_duration td)
	{ return td.total_milliseconds(); }
	inline boost::int64_t total_microseconds(time_duration td)
	{ return td.total_microseconds(); }

}

#else

#include <asio/time_traits.hpp>
#include <boost/cstdint.hpp>

namespace libtorrent
{
	// libtorrent time_duration type
	struct time_duration
	{
		time_duration() {}
		time_duration operator/(int rhs) const { return time_duration(diff / rhs); }
		explicit time_duration(boost::int64_t d) : diff(d) {}
		boost::int64_t diff;
	};

	inline bool is_negative(time_duration dt) { return dt.diff < 0; }
	inline bool operator<(time_duration lhs, time_duration rhs)
	{ return lhs.diff < rhs.diff; }
	inline bool operator>(time_duration lhs, time_duration rhs)
	{ return lhs.diff > rhs.diff; }

	// libtorrent time type
	struct ptime
	{
		ptime() {}
		explicit ptime(boost::int64_t t): time(t) {}
		boost::int64_t time;
	};

	inline bool operator>(ptime lhs, ptime rhs)
	{ return lhs.time > rhs.time; }
	inline bool operator>=(ptime lhs, ptime rhs)
	{ return lhs.time >= rhs.time; }
	inline bool operator<=(ptime lhs, ptime rhs)
	{ return lhs.time <= rhs.time; }
	inline bool operator<(ptime lhs, ptime rhs)
	{ return lhs.time < rhs.time; }
	inline bool operator!=(ptime lhs, ptime rhs)
	{ return lhs.time != rhs.time;}
	inline bool operator==(ptime lhs, ptime rhs)
	{ return lhs.time == rhs.time;}
	inline time_duration operator-(ptime lhs, ptime rhs)
	{ return time_duration(lhs.time - rhs.time); }
	inline ptime operator+(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time + rhs.diff); }
	inline ptime operator+(time_duration lhs, ptime rhs)
	{ return ptime(rhs.time + lhs.diff); }
	inline ptime operator-(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time - rhs.diff); }

	ptime time_now();
	inline ptime min_time() { return ptime(0); }
	inline ptime max_time() { return ptime((std::numeric_limits<boost::int64_t>::max)()); }
	int total_seconds(time_duration td);
	int total_milliseconds(time_duration td);
	boost::int64_t total_microseconds(time_duration td);
}

// asio time_traits
namespace asio
{
	template<>
	struct time_traits<libtorrent::ptime>
	{
		typedef libtorrent::ptime time_type;
		typedef libtorrent::time_duration duration_type;
		static time_type now()
		{ return time_type(libtorrent::time_now()); }
		static time_type add(time_type t, duration_type d)
		{ return time_type(t.time + d.diff);}
		static duration_type subtract(time_type t1, time_type t2)
		{ return duration_type(t1 - t2); }
		static bool less_than(time_type t1, time_type t2)
		{ return t1 < t2; }
		static boost::posix_time::time_duration to_posix_duration(
			duration_type d)
		{ return boost::posix_time::microseconds(libtorrent::total_microseconds(d)); }
	};
}

#if defined(__MACH__)

#include <mach/mach_time.h>
#include <boost/cstdint.hpp>

// high precision timer for darwin intel and ppc

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t absolutetime_to_microseconds(boost::int64_t at)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
				mach_timebase_info(&timebase_info);
			// make sure we don't overflow
			assert((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
				|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
			return at / 1000 * timebase_info.numer / timebase_info.denom;
		}

		inline boost::int64_t microseconds_to_absolutetime(boost::int64_t ms)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
			{
				mach_timebase_info(&timebase_info);
				assert(timebase_info.numer > 0);
				assert(timebase_info.denom > 0);
			}
			// make sure we don't overflow
			assert((ms >= 0 && ms <= ms * timebase_info.denom / timebase_info.numer * 1000)
				|| (ms < 0 && ms > ms * timebase_info.denom / timebase_info.numer * 1000));
			return ms * timebase_info.denom / timebase_info.numer * 1000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff);
	}

	inline ptime time_now() { return ptime(mach_absolute_time()); }

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60 * 60));
	}

}
#elif defined(_WIN32)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);

#ifndef NDEBUG
			// make sure we don't overflow
			boost::int64_t ret = (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
			assert((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));
#endif
			return (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
		}

		inline boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);
#ifndef NDEBUG
			// make sure we don't overflow
			boost::int64_t ret = (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
			assert((ms >= 0 && ms <= ret)
				|| (ms < 0 && ms > ret));
#endif
			return (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff);
	}

	inline ptime time_now()
	{
		LARGE_INTEGER now;
		QueryPerformanceCounter(&now);
		return ptime(now.QuadPart);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60 * 60));
	}

}

#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0

#include <time.h>

namespace libtorrent
{
	inline int total_seconds(time_duration td)
	{
		return td.diff / 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return td.diff / 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return td.diff;
	}

	inline ptime time_now()
	{
		timespec ts;
		clock_gettime(CLOCK_MONOTONIC, &ts);
		return ptime(boost::int64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(s);
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(s * 1000);
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(s * 1000000);
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(s * 1000000 * 60);
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(s * 1000000 * 60 * 60);
	}

}

#endif

#endif
#endif

<commit_msg>fixed a preprocessor condition bug where boost.date_time was being used when it shouldn't<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_TIME_HPP_INCLUDED
#define TORRENT_TIME_HPP_INCLUDED

#include <ctime>

#ifndef _WIN32
#include <unistd.h>
#endif

namespace libtorrent
{
	inline char const* time_now_string()
	{
		time_t t = std::time(0);
		tm* timeinfo = std::localtime(&t);
		static char str[200];
		std::strftime(str, 200, "%b %d %X", timeinfo);
		return str;
	}
}

#if (!defined (__MACH__) && !defined (_WIN32) && (!defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0)) || defined (TORRENT_USE_BOOST_DATE_TIME)

#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace libtorrent
{
	typedef boost::posix_time::ptime ptime;
	typedef boost::posix_time::time_duration time_duration;
	inline ptime time_now()
	{ return boost::posix_time::microsec_clock::universal_time(); }
	inline ptime min_time()
	{ return boost::posix_time::ptime(boost::posix_time::min_date_time); }
	inline ptime max_time()
	{ return boost::posix_time::ptime(boost::posix_time::max_date_time); }
	inline time_duration seconds(int s) { return boost::posix_time::seconds(s); }
	inline time_duration milliseconds(int s) { return boost::posix_time::milliseconds(s); }
	inline time_duration microsec(int s) { return boost::posix_time::microsec(s); }
	inline time_duration minutes(int s) { return boost::posix_time::minutes(s); }
	inline time_duration hours(int s) { return boost::posix_time::hours(s); }

	inline int total_seconds(time_duration td)
	{ return td.total_seconds(); }
	inline int total_milliseconds(time_duration td)
	{ return td.total_milliseconds(); }
	inline boost::int64_t total_microseconds(time_duration td)
	{ return td.total_microseconds(); }

}

#else

#include <asio/time_traits.hpp>
#include <boost/cstdint.hpp>

namespace libtorrent
{
	// libtorrent time_duration type
	struct time_duration
	{
		time_duration() {}
		time_duration operator/(int rhs) const { return time_duration(diff / rhs); }
		explicit time_duration(boost::int64_t d) : diff(d) {}
		boost::int64_t diff;
	};

	inline bool is_negative(time_duration dt) { return dt.diff < 0; }
	inline bool operator<(time_duration lhs, time_duration rhs)
	{ return lhs.diff < rhs.diff; }
	inline bool operator>(time_duration lhs, time_duration rhs)
	{ return lhs.diff > rhs.diff; }

	// libtorrent time type
	struct ptime
	{
		ptime() {}
		explicit ptime(boost::int64_t t): time(t) {}
		boost::int64_t time;
	};

	inline bool operator>(ptime lhs, ptime rhs)
	{ return lhs.time > rhs.time; }
	inline bool operator>=(ptime lhs, ptime rhs)
	{ return lhs.time >= rhs.time; }
	inline bool operator<=(ptime lhs, ptime rhs)
	{ return lhs.time <= rhs.time; }
	inline bool operator<(ptime lhs, ptime rhs)
	{ return lhs.time < rhs.time; }
	inline bool operator!=(ptime lhs, ptime rhs)
	{ return lhs.time != rhs.time;}
	inline bool operator==(ptime lhs, ptime rhs)
	{ return lhs.time == rhs.time;}
	inline time_duration operator-(ptime lhs, ptime rhs)
	{ return time_duration(lhs.time - rhs.time); }
	inline ptime operator+(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time + rhs.diff); }
	inline ptime operator+(time_duration lhs, ptime rhs)
	{ return ptime(rhs.time + lhs.diff); }
	inline ptime operator-(ptime lhs, time_duration rhs)
	{ return ptime(lhs.time - rhs.diff); }

	ptime time_now();
	inline ptime min_time() { return ptime(0); }
	inline ptime max_time() { return ptime((std::numeric_limits<boost::int64_t>::max)()); }
	int total_seconds(time_duration td);
	int total_milliseconds(time_duration td);
	boost::int64_t total_microseconds(time_duration td);
}

// asio time_traits
namespace asio
{
	template<>
	struct time_traits<libtorrent::ptime>
	{
		typedef libtorrent::ptime time_type;
		typedef libtorrent::time_duration duration_type;
		static time_type now()
		{ return time_type(libtorrent::time_now()); }
		static time_type add(time_type t, duration_type d)
		{ return time_type(t.time + d.diff);}
		static duration_type subtract(time_type t1, time_type t2)
		{ return duration_type(t1 - t2); }
		static bool less_than(time_type t1, time_type t2)
		{ return t1 < t2; }
		static boost::posix_time::time_duration to_posix_duration(
			duration_type d)
		{ return boost::posix_time::microseconds(libtorrent::total_microseconds(d)); }
	};
}

#if defined(__MACH__)

#include <mach/mach_time.h>
#include <boost/cstdint.hpp>

// high precision timer for darwin intel and ppc

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t absolutetime_to_microseconds(boost::int64_t at)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
				mach_timebase_info(&timebase_info);
			// make sure we don't overflow
			assert((at >= 0 && at >= at / 1000 * timebase_info.numer / timebase_info.denom)
				|| (at < 0 && at < at / 1000 * timebase_info.numer / timebase_info.denom));
			return at / 1000 * timebase_info.numer / timebase_info.denom;
		}

		inline boost::int64_t microseconds_to_absolutetime(boost::int64_t ms)
		{
			static mach_timebase_info_data_t timebase_info = {0,0};
			if (timebase_info.denom == 0)
			{
				mach_timebase_info(&timebase_info);
				assert(timebase_info.numer > 0);
				assert(timebase_info.denom > 0);
			}
			// make sure we don't overflow
			assert((ms >= 0 && ms <= ms * timebase_info.denom / timebase_info.numer * 1000)
				|| (ms < 0 && ms > ms * timebase_info.denom / timebase_info.numer * 1000));
			return ms * timebase_info.denom / timebase_info.numer * 1000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::absolutetime_to_microseconds(td.diff);
	}

	inline ptime time_now() { return ptime(mach_absolute_time()); }

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_absolutetime(s * 1000000 * 60 * 60));
	}

}
#elif defined(_WIN32)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>

namespace libtorrent
{
	namespace aux
	{
		inline boost::int64_t performance_counter_to_microseconds(boost::int64_t pc)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);

#ifndef NDEBUG
			// make sure we don't overflow
			boost::int64_t ret = (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
			assert((pc >= 0 && pc >= ret) || (pc < 0 && pc < ret));
#endif
			return (pc * 1000 / performace_counter_frequency.QuadPart) * 1000;
		}

		inline boost::int64_t microseconds_to_performance_counter(boost::int64_t ms)
		{
			static LARGE_INTEGER performace_counter_frequency = {0,0};
			if (performace_counter_frequency.QuadPart == 0)
				QueryPerformanceFrequency(&performace_counter_frequency);
#ifndef NDEBUG
			// make sure we don't overflow
			boost::int64_t ret = (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
			assert((ms >= 0 && ms <= ret)
				|| (ms < 0 && ms > ret));
#endif
			return (ms / 1000) * performace_counter_frequency.QuadPart / 1000;
		}
	}

	inline int total_seconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff)
			/ 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return aux::performance_counter_to_microseconds(td.diff);
	}

	inline ptime time_now()
	{
		LARGE_INTEGER now;
		QueryPerformanceCounter(&now);
		return ptime(now.QuadPart);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(s));
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000));
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000));
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60));
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(aux::microseconds_to_performance_counter(
			s * 1000000 * 60 * 60));
	}

}

#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0

#include <time.h>

namespace libtorrent
{
	inline int total_seconds(time_duration td)
	{
		return td.diff / 1000000;
	}
	inline int total_milliseconds(time_duration td)
	{
		return td.diff / 1000;
	}
	inline boost::int64_t total_microseconds(time_duration td)
	{
		return td.diff;
	}

	inline ptime time_now()
	{
		timespec ts;
		clock_gettime(CLOCK_MONOTONIC, &ts);
		return ptime(boost::int64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000);
	}

	inline time_duration microsec(boost::int64_t s)
	{
		return time_duration(s);
	}
	inline time_duration milliseconds(boost::int64_t s)
	{
		return time_duration(s * 1000);
	}
	inline time_duration seconds(boost::int64_t s)
	{
		return time_duration(s * 1000000);
	}
	inline time_duration minutes(boost::int64_t s)
	{
		return time_duration(s * 1000000 * 60);
	}
	inline time_duration hours(boost::int64_t s)
	{
		return time_duration(s * 1000000 * 60 * 60);
	}

}

#endif

#endif
#endif

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GEOMETRY_HPP
#define MAPNIK_GEOMETRY_HPP

// mapnik
#include <mapnik/vertex_vector.hpp>
#include <mapnik/geom_util.hpp>

// boost
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

namespace mapnik {

enum eGeomType {
    Point = 1,
    LineString = 2,
    Polygon = 3
};

template <typename T, template <typename> class Container=vertex_vector>
class geometry
{
public:
    typedef T coord_type;
    typedef Container<coord_type> container_type;
    typedef typename container_type::value_type value_type;

private:
    container_type cont_;
    eGeomType type_;
    mutable unsigned itr_;
public:

    geometry(eGeomType type)
        : type_(type),
          itr_(0)
    {}

    eGeomType type() const
    {
        return type_;
    }

    container_type const& data() const
    {
        return cont_;
    }

    box2d<double> envelope() const
    {
        box2d<double> result;
        double x(0);
        double y(0);
        rewind(0);
        for (unsigned i=0;i<num_points();++i)
        {
            vertex(&x,&y);
            if (i==0)
            {
                result.init(x,y,x,y);
            }
            else
            {
                result.expand_to_include(x,y);
            }
        }
        return result;
    }

    void label_interior_position(double *x, double *y) const
    {
        // start with the default label position
        label_position(x,y);
        unsigned size = cont_.size();
        // if we are not a polygon, or the default is within the polygon we are done
        if (size < 3 || hit_test(*x,*y,0))
            return;

        // otherwise we find a horizontal line across the polygon and then return the
        // center of the widest intersection between the polygon and the line.

        std::vector<double> intersections; // only need to store the X as we know the y

        double x0=0;
        double y0=0;
        rewind(0);
        unsigned command = vertex(&x0, &y0);
        double x1,y1;
        while (SEG_END != (command=vertex(&x1, &y1)))
        {
            if (command != SEG_MOVETO)
            {
                // if the segments overlap
                if (y0==y1)
                {
                    if (y0==*y)
                    {
                        double xi = (x0+x1)/2.0;
                        intersections.push_back(xi);
                    }
                }
                // if the path segment crosses the bisector
                else if ((y0 <= *y && y1 >= *y) ||
                        (y0 >= *y && y1 <= *y))
                {
                    // then calculate the intersection
                    double xi = x0;
                    if (x0 != x1)
                    {
                        double m = (y1-y0)/(x1-x0);
                        double c = y0 - m*x0;
                        xi = (*y-c)/m;
                    }

                    intersections.push_back(xi);
                }
            }
            x0 = x1;
            y0 = y1;
        }
        // no intersections we just return the default
        if (intersections.empty())
            return;
        x0=intersections[0];
        double max_width = 0;
        for (unsigned ii = 1; ii < intersections.size(); ++ii)
        {
            double x1=intersections[ii];
            double xc=(x0+x1)/2.0;
            double width = fabs(x1-x0);
            if (width > max_width && hit_test(xc,*y,0))
            {
                *x=xc;
                max_width = width;
            }
        }
    }

    /* center of gravity centroid
      - best visually but does not work with multipolygons
    */
    void label_position(double *x, double *y) const
    {
        if (type_ == LineString)
        {
            middle_point(x,y);
            return;
        }

        unsigned size = cont_.size();
        if (size < 3)
        {
            cont_.get_vertex(0,x,y);
            return;
        }

        double ai;
        double atmp = 0;
        double xtmp = 0;
        double ytmp = 0;
        double x0 =0;
        double y0 =0;
        double x1 =0;
        double y1 =0;
        double ox =0;
        double oy =0;

        unsigned i;

        // Use first point as origin to improve numerical accuracy
        cont_.get_vertex(0,&ox,&oy);

        for (i = 0; i < size-1; i++)
        {
            cont_.get_vertex(i,&x0,&y0);
            cont_.get_vertex(i+1,&x1,&y1);

            x0 -= ox; y0 -= oy;
            x1 -= ox; y1 -= oy;

            ai = x0 * y1 - x1 * y0;
            atmp += ai;
            xtmp += (x1 + x0) * ai;
            ytmp += (y1 + y0) * ai;
        }
        if (atmp != 0)
        {
            *x = (xtmp/(3*atmp)) + ox;
            *y = (ytmp/(3*atmp)) + oy;
            return;
        }
        *x=x0;
        *y=y0;
    }

    /* center of bounding box centroid */
    void label_position2(double *x, double *y) const
    {

        box2d<double> box = envelope();
        *x = box.center().x;
        *y = box.center().y;
    }

    /* summarized distance centroid */
    void label_position3(double *x, double *y) const
    {
        if (type_ == LineString)
        {
            middle_point(x,y);
            return;
        }

        unsigned i = 0;
        double l = 0.0;
        double tl = 0.0;
        double cx = 0.0;
        double cy = 0.0;
        double x0 = 0.0;
        double y0 = 0.0;
        double x1 = 0.0;
        double y1 = 0.0;
        unsigned size = cont_.size();
        for (i = 0; i < size-1; i++)
        {
            cont_.get_vertex(i,&x0,&y0);
            cont_.get_vertex(i+1,&x1,&y1);
            l = distance(x0,y0,x1,y1);
            cx += l * (x1 + x0)/2;
            cy += l * (y1 + y0)/2;
            tl += l;
        }
        *x = cx / tl;
        *y = cy / tl;
    }

    void middle_point(double *x, double *y) const
    {
        // calculate mid point on path
        double x0=0;
        double y0=0;
        double x1=0;
        double y1=0;

        unsigned size = cont_.size();
        if (size == 1)
        {
            cont_.get_vertex(0,x,y);
        }
        else if (size == 2)
        {
            cont_.get_vertex(0,&x0,&y0);
            cont_.get_vertex(1,&x1,&y1);
            *x = 0.5 * (x1 + x0);
            *y = 0.5 * (y1 + y0);
        }
        else
        {
            double len=0.0;
            for (unsigned pos = 1; pos < size; ++pos)
            {
                cont_.get_vertex(pos-1,&x0,&y0);
                cont_.get_vertex(pos,&x1,&y1);
                double dx = x1 - x0;
                double dy = y1 - y0;
                len += std::sqrt(dx * dx + dy * dy);
            }
            double midlen = 0.5 * len;
            double dist = 0.0;
            for (unsigned pos = 1; pos < size;++pos)
            {
                cont_.get_vertex(pos-1,&x0,&y0);
                cont_.get_vertex(pos,&x1,&y1);
                double dx = x1 - x0;
                double dy = y1 - y0;
                double seg_len = std::sqrt(dx * dx + dy * dy);
                if (( dist + seg_len) >= midlen)
                {
                    double r = (midlen - dist)/seg_len;
                    *x = x0 + (x1 - x0) * r;
                    *y = y0 + (y1 - y0) * r;
                    break;
                }
                dist += seg_len;
            }
        }
    }

    void push_vertex(coord_type x, coord_type y, CommandType c)
    {
        cont_.push_back(x,y,c);
    }

    void line_to(coord_type x,coord_type y)
    {
        push_vertex(x,y,SEG_LINETO);
    }

    void move_to(coord_type x,coord_type y)
    {
        push_vertex(x,y,SEG_MOVETO);
    }

    unsigned num_points() const
    {
        return cont_.size();
    }

    unsigned vertex(double* x, double* y) const
    {
        return cont_.get_vertex(itr_++,x,y);
    }

    unsigned get_vertex(unsigned pos, double* x, double* y) const
    {
        return cont_.get_vertex(pos, x, y);
    }

    void rewind(unsigned ) const
    {
        itr_=0;
    }

    bool hit_test(coord_type x, coord_type y, double tol) const
    {
        if (cont_.size() == 1) {
            // Handle points
            double x0, y0;
            cont_.get_vertex(0, &x0, &y0);
            return distance(x, y, x0, y0) <= fabs(tol);
        } else if (cont_.size() > 1) {
            bool inside=false;
            double x0=0;
            double y0=0;
            rewind(0);
            vertex(&x0, &y0);

            unsigned command;
            double x1,y1;
            while (SEG_END != (command=vertex(&x1, &y1)))
            {
                if (command == SEG_MOVETO)
                {
                    x0 = x1;
                    y0 = y1;
                    continue;
                }
                if ((((y1 <= y) && (y < y0)) ||
                     ((y0 <= y) && (y < y1))) &&
                    ( x < (x0 - x1) * (y - y1)/ (y0 - y1) + x1))
                    inside=!inside;
                x0=x1;
                y0=y1;
            }
            return inside;
        }
        return false;
    }

    void set_capacity(size_t size)
    {
        cont_.set_capacity(size);
    }
};

typedef geometry<double,vertex_vector> geometry_type;
typedef boost::shared_ptr<geometry_type> geometry_ptr;
typedef boost::ptr_vector<geometry_type> geometry_containter;

}

#endif // MAPNIK_GEOMETRY_HPP
<commit_msg>+ make geometry noncopyable + make ctor explicit<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GEOMETRY_HPP
#define MAPNIK_GEOMETRY_HPP

// mapnik
#include <mapnik/vertex_vector.hpp>
#include <mapnik/geom_util.hpp>

// boost
#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

namespace mapnik {

enum eGeomType {
    Point = 1,
    LineString = 2,
    Polygon = 3
};

template <typename T, template <typename> class Container=vertex_vector>
class geometry : private::noncopyable
{
public:
    typedef T coord_type;
    typedef Container<coord_type> container_type;
    typedef typename container_type::value_type value_type;

private:
    container_type cont_;
    eGeomType type_;
    mutable unsigned itr_;
public:

    explicit geometry(eGeomType type)
        : type_(type),
          itr_(0)
    {}

    eGeomType type() const
    {
        return type_;
    }

    container_type const& data() const
    {
        return cont_;
    }

    box2d<double> envelope() const
    {
        box2d<double> result;
        double x(0);
        double y(0);
        rewind(0);
        for (unsigned i=0;i<num_points();++i)
        {
            vertex(&x,&y);
            if (i==0)
            {
                result.init(x,y,x,y);
            }
            else
            {
                result.expand_to_include(x,y);
            }
        }
        return result;
    }

    void label_interior_position(double *x, double *y) const
    {
        // start with the default label position
        label_position(x,y);
        unsigned size = cont_.size();
        // if we are not a polygon, or the default is within the polygon we are done
        if (size < 3 || hit_test(*x,*y,0))
            return;

        // otherwise we find a horizontal line across the polygon and then return the
        // center of the widest intersection between the polygon and the line.

        std::vector<double> intersections; // only need to store the X as we know the y

        double x0=0;
        double y0=0;
        rewind(0);
        unsigned command = vertex(&x0, &y0);
        double x1,y1;
        while (SEG_END != (command=vertex(&x1, &y1)))
        {
            if (command != SEG_MOVETO)
            {
                // if the segments overlap
                if (y0==y1)
                {
                    if (y0==*y)
                    {
                        double xi = (x0+x1)/2.0;
                        intersections.push_back(xi);
                    }
                }
                // if the path segment crosses the bisector
                else if ((y0 <= *y && y1 >= *y) ||
                        (y0 >= *y && y1 <= *y))
                {
                    // then calculate the intersection
                    double xi = x0;
                    if (x0 != x1)
                    {
                        double m = (y1-y0)/(x1-x0);
                        double c = y0 - m*x0;
                        xi = (*y-c)/m;
                    }

                    intersections.push_back(xi);
                }
            }
            x0 = x1;
            y0 = y1;
        }
        // no intersections we just return the default
        if (intersections.empty())
            return;
        x0=intersections[0];
        double max_width = 0;
        for (unsigned ii = 1; ii < intersections.size(); ++ii)
        {
            double x1=intersections[ii];
            double xc=(x0+x1)/2.0;
            double width = fabs(x1-x0);
            if (width > max_width && hit_test(xc,*y,0))
            {
                *x=xc;
                max_width = width;
            }
        }
    }

    /* center of gravity centroid
      - best visually but does not work with multipolygons
    */
    void label_position(double *x, double *y) const
    {
        if (type_ == LineString)
        {
            middle_point(x,y);
            return;
        }

        unsigned size = cont_.size();
        if (size < 3)
        {
            cont_.get_vertex(0,x,y);
            return;
        }

        double ai;
        double atmp = 0;
        double xtmp = 0;
        double ytmp = 0;
        double x0 =0;
        double y0 =0;
        double x1 =0;
        double y1 =0;
        double ox =0;
        double oy =0;

        unsigned i;

        // Use first point as origin to improve numerical accuracy
        cont_.get_vertex(0,&ox,&oy);

        for (i = 0; i < size-1; i++)
        {
            cont_.get_vertex(i,&x0,&y0);
            cont_.get_vertex(i+1,&x1,&y1);

            x0 -= ox; y0 -= oy;
            x1 -= ox; y1 -= oy;

            ai = x0 * y1 - x1 * y0;
            atmp += ai;
            xtmp += (x1 + x0) * ai;
            ytmp += (y1 + y0) * ai;
        }
        if (atmp != 0)
        {
            *x = (xtmp/(3*atmp)) + ox;
            *y = (ytmp/(3*atmp)) + oy;
            return;
        }
        *x=x0;
        *y=y0;
    }

    /* center of bounding box centroid */
    void label_position2(double *x, double *y) const
    {

        box2d<double> box = envelope();
        *x = box.center().x;
        *y = box.center().y;
    }

    /* summarized distance centroid */
    void label_position3(double *x, double *y) const
    {
        if (type_ == LineString)
        {
            middle_point(x,y);
            return;
        }

        unsigned i = 0;
        double l = 0.0;
        double tl = 0.0;
        double cx = 0.0;
        double cy = 0.0;
        double x0 = 0.0;
        double y0 = 0.0;
        double x1 = 0.0;
        double y1 = 0.0;
        unsigned size = cont_.size();
        for (i = 0; i < size-1; i++)
        {
            cont_.get_vertex(i,&x0,&y0);
            cont_.get_vertex(i+1,&x1,&y1);
            l = distance(x0,y0,x1,y1);
            cx += l * (x1 + x0)/2;
            cy += l * (y1 + y0)/2;
            tl += l;
        }
        *x = cx / tl;
        *y = cy / tl;
    }

    void middle_point(double *x, double *y) const
    {
        // calculate mid point on path
        double x0=0;
        double y0=0;
        double x1=0;
        double y1=0;

        unsigned size = cont_.size();
        if (size == 1)
        {
            cont_.get_vertex(0,x,y);
        }
        else if (size == 2)
        {
            cont_.get_vertex(0,&x0,&y0);
            cont_.get_vertex(1,&x1,&y1);
            *x = 0.5 * (x1 + x0);
            *y = 0.5 * (y1 + y0);
        }
        else
        {
            double len=0.0;
            for (unsigned pos = 1; pos < size; ++pos)
            {
                cont_.get_vertex(pos-1,&x0,&y0);
                cont_.get_vertex(pos,&x1,&y1);
                double dx = x1 - x0;
                double dy = y1 - y0;
                len += std::sqrt(dx * dx + dy * dy);
            }
            double midlen = 0.5 * len;
            double dist = 0.0;
            for (unsigned pos = 1; pos < size;++pos)
            {
                cont_.get_vertex(pos-1,&x0,&y0);
                cont_.get_vertex(pos,&x1,&y1);
                double dx = x1 - x0;
                double dy = y1 - y0;
                double seg_len = std::sqrt(dx * dx + dy * dy);
                if (( dist + seg_len) >= midlen)
                {
                    double r = (midlen - dist)/seg_len;
                    *x = x0 + (x1 - x0) * r;
                    *y = y0 + (y1 - y0) * r;
                    break;
                }
                dist += seg_len;
            }
        }
    }

    void push_vertex(coord_type x, coord_type y, CommandType c)
    {
        cont_.push_back(x,y,c);
    }

    void line_to(coord_type x,coord_type y)
    {
        push_vertex(x,y,SEG_LINETO);
    }

    void move_to(coord_type x,coord_type y)
    {
        push_vertex(x,y,SEG_MOVETO);
    }

    unsigned num_points() const
    {
        return cont_.size();
    }

    unsigned vertex(double* x, double* y) const
    {
        return cont_.get_vertex(itr_++,x,y);
    }

    unsigned get_vertex(unsigned pos, double* x, double* y) const
    {
        return cont_.get_vertex(pos, x, y);
    }

    void rewind(unsigned ) const
    {
        itr_=0;
    }

    bool hit_test(coord_type x, coord_type y, double tol) const
    {
        if (cont_.size() == 1) {
            // Handle points
            double x0, y0;
            cont_.get_vertex(0, &x0, &y0);
            return distance(x, y, x0, y0) <= fabs(tol);
        } else if (cont_.size() > 1) {
            bool inside=false;
            double x0=0;
            double y0=0;
            rewind(0);
            vertex(&x0, &y0);

            unsigned command;
            double x1,y1;
            while (SEG_END != (command=vertex(&x1, &y1)))
            {
                if (command == SEG_MOVETO)
                {
                    x0 = x1;
                    y0 = y1;
                    continue;
                }
                if ((((y1 <= y) && (y < y0)) ||
                     ((y0 <= y) && (y < y1))) &&
                    ( x < (x0 - x1) * (y - y1)/ (y0 - y1) + x1))
                    inside=!inside;
                x0=x1;
                y0=y1;
            }
            return inside;
        }
        return false;
    }

    void set_capacity(size_t size)
    {
        cont_.set_capacity(size);
    }
};

typedef geometry<double,vertex_vector> geometry_type;
typedef boost::shared_ptr<geometry_type> geometry_ptr;
typedef boost::ptr_vector<geometry_type> geometry_containter;

}

#endif // MAPNIK_GEOMETRY_HPP
<|endoftext|>


<commit_before>#pragma once

#ifndef SIPL_MATRIX_WRAPPERS_H
#define SIPL_MATRIX_WRAPPERS_H

#include <algorithm>
#include <cassert>

// Wrapper for Dtype*. Need this so we can use the regular VectorBase calls.
// XXX include extra int32_t type so we can swap this with StaticArrayWrapper
// freely
template <typename Dtype, int32_t>
struct DynamicArrayWrapper {
    Dtype* data_;
    int32_t size_;

    DynamicArrayWrapper() : data_(nullptr) {}

    DynamicArrayWrapper(int32_t size) : data_(new Dtype[size]), size_(size) {}

    DynamicArrayWrapper(const DynamicArrayWrapper& other)
        : data_(new Dtype[other.size_]), size_(other.size_)
    {
        std::copy(std::begin(other), std::end(other), data_);
    }

    DynamicArrayWrapper(DynamicArrayWrapper&& other)
        : data_(std::move(other.data_)), size_(other.size_)
    {
        other.data_ = nullptr;
        other.size_ = 0;
    }

    DynamicArrayWrapper& operator=(const DynamicArrayWrapper& other)
    {
        if (data_ != nullptr) {
            delete[] data_;
        }
        data_ = new Dtype[other.size_];
        size_ = other.size_;
        std::copy(std::begin(other), std::end(other), data_);
        return *this;
    }

    DynamicArrayWrapper& operator=(DynamicArrayWrapper&& other)
    {
        data_ = std::move(other.data_);
        size_ = other.size_;
        other.data_ = nullptr;
        other.size_ = 0;
        return *this;
    }

    Dtype* begin() { return data_; }
    const Dtype* begin() const { return data_; }

    Dtype* end() { return data_ + size_; }
    const Dtype* end() const { return data_ + size_; }

    int32_t size() const { return size_; }

    Dtype& operator[](int32_t index) { return data_[index]; }
    const Dtype& operator[](int32_t index) const { return data_[index]; }

    Dtype& operator()(int32_t index) { return data_[index]; }
    const Dtype& operator()(int32_t index) const { return data_[index]; }

    Dtype* data() { return data_; }
    const Dtype* data() const { return data_; }

    Dtype& front()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }

    const Dtype& front() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }

    Dtype& back()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }

    const Dtype& back() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }
};

// Wrapper for Dtype*. Need this so we can use the regular VectorBase calls.
template <typename Dtype, int32_t Length>
struct StaticArrayWrapper {
    std::array<Dtype, Length> data_;
    int32_t size_;

    StaticArrayWrapper() : data_(), size_(Length) {}

    StaticArrayWrapper(int32_t size) : data_(), size_(Length)
    {
        assert(size == Length && "size mismatch");
    }

    StaticArrayWrapper(const StaticArrayWrapper& other)
        : data_(), size_(other.size_)
    {
        std::copy(std::begin(other), std::end(other), std::begin(data_));
    }

    StaticArrayWrapper(StaticArrayWrapper&& other)
        : data_(std::move(other.data_)), size_(other.size_)
    {
        other.size_ = 0;
    }

    StaticArrayWrapper& operator=(const StaticArrayWrapper& other)
    {
        size_ = other.size_;
        std::copy(std::begin(other), std::end(other), std::begin(data_));
        return *this;
    }

    StaticArrayWrapper& operator=(StaticArrayWrapper&& other)
    {
        data_ = std::move(other.data_);
        size_ = other.size_;
        other.size_ = 0;
        return *this;
    }

    Dtype* begin() { return data_.begin(); }
    const Dtype* begin() const { return data_.begin(); }

    Dtype* end() { return data_.end(); }
    const Dtype* end() const { return data_.end(); }

    int32_t size() const { return size_; }

    Dtype& operator[](int32_t index) { return data_[index]; }
    const Dtype& operator[](int32_t index) const { return data_[index]; }

    Dtype& operator()(int32_t index) { return data_[index]; }
    const Dtype& operator()(int32_t index) const { return data_[index]; }

    Dtype* data() { return data_.data(); }
    const Dtype* data() const { return data_.data(); }

    Dtype& front()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }
    const Dtype& front() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }

    Dtype& back()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }
    const Dtype& back() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }
};

#endif
<commit_msg>Fixes for Win10<commit_after>#pragma once

#ifndef SIPL_MATRIX_WRAPPERS_H
#define SIPL_MATRIX_WRAPPERS_H

#include <algorithm>
#include <cassert>

// Wrapper for Dtype*. Need this so we can use the regular VectorBase calls.
// XXX include extra int32_t type so we can swap this with StaticArrayWrapper
// freely
template <typename Dtype, int32_t>
struct DynamicArrayWrapper {
    Dtype* data_;
    int32_t size_;

    DynamicArrayWrapper() : data_(nullptr) {}

    DynamicArrayWrapper(int32_t size) : data_(new Dtype[size]), size_(size) {}

    DynamicArrayWrapper(const DynamicArrayWrapper& other)
        : data_(new Dtype[other.size_]), size_(other.size_)
    {
        std::copy(std::begin(other), std::end(other), data_);
    }

    DynamicArrayWrapper(DynamicArrayWrapper&& other)
        : data_(std::move(other.data_)), size_(other.size_)
    {
        other.data_ = nullptr;
        other.size_ = 0;
    }

    DynamicArrayWrapper& operator=(const DynamicArrayWrapper& other)
    {
        if (data_ != nullptr) {
            delete[] data_;
        }
        data_ = new Dtype[other.size_];
        size_ = other.size_;
        std::copy(std::begin(other), std::end(other), data_);
        return *this;
    }

    DynamicArrayWrapper& operator=(DynamicArrayWrapper&& other)
    {
        data_ = std::move(other.data_);
        size_ = other.size_;
        other.data_ = nullptr;
        other.size_ = 0;
        return *this;
    }

    Dtype* begin() { return data_; }
    const Dtype* begin() const { return data_; }

    Dtype* end() { return data_ + size_; }
    const Dtype* end() const { return data_ + size_; }

    int32_t size() const { return size_; }

    Dtype& operator[](int32_t index) { return data_[index]; }
    const Dtype& operator[](int32_t index) const { return data_[index]; }

    Dtype& operator()(int32_t index) { return data_[index]; }
    const Dtype& operator()(int32_t index) const { return data_[index]; }

    Dtype* data() { return data_; }
    const Dtype* data() const { return data_; }

    Dtype& front()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }

    const Dtype& front() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }

    Dtype& back()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }

    const Dtype& back() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }
};

// Wrapper for Dtype*. Need this so we can use the regular VectorBase calls.
template <typename Dtype, int32_t Length>
struct StaticArrayWrapper {
    std::array<Dtype, Length> data_;
    int32_t size_;

    StaticArrayWrapper() : data_(), size_(Length) {}

    StaticArrayWrapper(int32_t size) : data_(), size_(Length)
    {
        assert(size == Length && "size mismatch");
    }

    StaticArrayWrapper(const StaticArrayWrapper& other)
        : data_(), size_(other.size_)
    {
        std::copy(std::begin(other), std::end(other), std::begin(data_));
    }

    StaticArrayWrapper(StaticArrayWrapper&& other)
        : data_(std::move(other.data_)), size_(other.size_)
    {
        other.size_ = 0;
    }

    StaticArrayWrapper& operator=(const StaticArrayWrapper& other)
    {
        size_ = other.size_;
        std::copy(std::begin(other), std::end(other), std::begin(data_));
        return *this;
    }

    StaticArrayWrapper& operator=(StaticArrayWrapper&& other)
    {
        data_ = std::move(other.data_);
        size_ = other.size_;
        other.size_ = 0;
        return *this;
    }

    Dtype* begin() { return data_.data(); }
    const Dtype* begin() const { return data_.data(); }

    Dtype* end() { return begin() + size_; }
    const Dtype* end() const { return begin() + size_; }

    int32_t size() const { return size_; }

    Dtype& operator[](int32_t index) { return data_[index]; }
    const Dtype& operator[](int32_t index) const { return data_[index]; }

    Dtype& operator()(int32_t index) { return data_[index]; }
    const Dtype& operator()(int32_t index) const { return data_[index]; }

    Dtype* data() { return data_.data(); }
    const Dtype* data() const { return data_.data(); }

    Dtype& front()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }
    const Dtype& front() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[0];
    }

    Dtype& back()
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }
    const Dtype& back() const
    {
        assert(size_ > 0 && "size mismatch");
        return data_[size_ - 1];
    }
};

#endif
<|endoftext|>