<commit_before>/*

Copyright (c) 2003-2008, 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_TORRENT_INFO_HPP_INCLUDED
#define TORRENT_TORRENT_INFO_HPP_INCLUDED

#include <string>
#include <vector>
#include <iosfwd>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/optional.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/shared_array.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/entry.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/size_type.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/intrusive_ptr_base.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/file_storage.hpp"

namespace libtorrent
{
	namespace pt = boost::posix_time;
	namespace gr = boost::gregorian;
	namespace fs = boost::filesystem;

	enum
	{
		// wait 60 seconds before retrying a failed tracker
		tracker_retry_delay_min = 10
		// when tracker_failed_max trackers
		// has failed, wait 60 minutes instead
		, tracker_retry_delay_max = 60 * 60
	};

	struct TORRENT_EXPORT announce_entry
	{
		announce_entry(std::string const& u)
			: url(u)
			, tier(0)
			, fail_limit(3)
			, fails(0)
			, source(0)
			, verified(false)
			, updating(false)
			, start_sent(false)
			, complete_sent(false)
		{}

		std::string url;

		// the time of next tracker announce
		ptime next_announce;

		boost::uint8_t tier;
		// the number of times this tracker can fail
		// in a row before it's removed. 0 means unlimited
		boost::uint8_t fail_limit;

		// the number of times in a row this tracker has failed
		boost::uint8_t fails;

		enum tracker_source
		{
			source_torrent = 1,
			source_client = 2,
			source_magnet_link = 4,
			source_tex = 8
		};
		// where did we get this tracker from
		boost::uint8_t source;

		// is set to true if we have ever received a response from
		// this tracker
		bool verified:1;

		// true if we're currently trying to announce with
		// this tracker
		bool updating:1;

		// this is true if event start has been sent to the tracker
		bool start_sent:1;

		// this is true if event completed has been sent to the tracker
		bool complete_sent:1;

		void reset()
		{
			start_sent = false;
			next_announce = min_time();
		}

		void failed()
		{
			++fails;
			int delay = (std::min)(tracker_retry_delay_min + int(fails) * int(fails) * tracker_retry_delay_min
				, int(tracker_retry_delay_max));
			next_announce = time_now() + seconds(delay);
			updating = false;
		}

		bool can_announce(ptime now) const
		{
			return now >= next_announce
				&& (fails < fail_limit || fail_limit == 0)
				&& !updating;
		}

		bool is_working() const
		{
			return fails == 0;
		}
	};

#ifndef BOOST_NO_EXCEPTIONS
	// for backwards compatibility with 0.14
	typedef libtorrent_exception invalid_torrent_file;
#endif

	int TORRENT_EXPORT load_file(fs::path const& filename, std::vector<char>& v);

	class TORRENT_EXPORT torrent_info : public intrusive_ptr_base<torrent_info>
	{
	public:
#ifndef BOOST_NO_EXCEPTIONS
		torrent_info(lazy_entry const& torrent_file);
		torrent_info(char const* buffer, int size);
		torrent_info(fs::path const& filename);
#ifndef BOOST_FILESYSTEM_NARROW_ONLY
		torrent_info(fs::wpath const& filename);
#endif
#endif

		torrent_info(sha1_hash const& info_hash);
		torrent_info(lazy_entry const& torrent_file, error_code& ec);
		torrent_info(char const* buffer, int size, error_code& ec);
		torrent_info(fs::path const& filename, error_code& ec);
#ifndef BOOST_FILESYSTEM_NARROW_ONLY
		torrent_info(fs::wpath const& filename, error_code& ec);
#endif

		~torrent_info();

		file_storage const& files() const { return m_files; }
		file_storage const& orig_files() const { return m_orig_files ? *m_orig_files : m_files; }

		void rename_file(int index, std::string const& new_filename)
		{
			copy_on_write();
			m_files.rename_file(index, new_filename);
		}

#ifndef BOOST_FILESYSTEM_NARROW_ONLY
		void rename_file(int index, std::wstring const& new_filename)
		{
			copy_on_write();
			m_files.rename_file(index, new_filename);
		}
#endif

		void add_tracker(std::string const& url, int tier = 0);
		std::vector<announce_entry> const& trackers() const { return m_urls; }

		std::vector<std::string> const& url_seeds() const
		{ return m_url_seeds; }
		void add_url_seed(std::string const& url)
		{ m_url_seeds.push_back(url); }

		std::vector<std::string> const& http_seeds() const
		{ return m_http_seeds; }
		void add_http_seed(std::string const& url)
		{ m_http_seeds.push_back(url); }

		size_type total_size() const { return m_files.total_size(); }
		int piece_length() const { return m_files.piece_length(); }
		int num_pieces() const { return m_files.num_pieces(); }
		const sha1_hash& info_hash() const { return m_info_hash; }
		const std::string& name() const { return m_files.name(); }

		typedef file_storage::iterator file_iterator;
		typedef file_storage::reverse_iterator reverse_file_iterator;

		file_iterator begin_files() const { return m_files.begin(); }
		file_iterator end_files() const { return m_files.end(); }
		reverse_file_iterator rbegin_files() const { return m_files.rbegin(); }
		reverse_file_iterator rend_files() const { return m_files.rend(); }
		int num_files() const { return m_files.num_files(); }
		file_entry const& file_at(int index) const { return m_files.at(index); }

		file_iterator file_at_offset(size_type offset) const
		{ return m_files.file_at_offset(offset); }
		std::vector<file_slice> map_block(int piece, size_type offset, int size) const
		{ return m_files.map_block(piece, offset, size); }
		peer_request map_file(int file, size_type offset, int size) const
		{ return m_files.map_file(file, offset, size); }

#ifndef TORRENT_NO_DEPRECATE
// ------- start deprecation -------
// these functions will be removed in a future version
		torrent_info(entry const& torrent_file) TORRENT_DEPRECATED;
		void print(std::ostream& os) const TORRENT_DEPRECATED;
// ------- end deprecation -------
#endif

		bool is_valid() const { return m_files.is_valid(); }

		bool priv() const { return m_private; }

		int piece_size(int index) const { return m_files.piece_size(index); }

		sha1_hash hash_for_piece(int index) const
		{ return sha1_hash(hash_for_piece_ptr(index)); }

		std::vector<sha1_hash> const& merkle_tree() const { return m_merkle_tree; }
		void set_merkle_tree(std::vector<sha1_hash>& h)
		{ TORRENT_ASSERT(h.size() == m_merkle_tree.size() ); m_merkle_tree.swap(h); }

		char const* hash_for_piece_ptr(int index) const
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_files.num_pieces());
			if (is_merkle_torrent())
			{
				TORRENT_ASSERT(index < int(m_merkle_tree.size()) - m_merkle_first_leaf);
				return (const char*)&m_merkle_tree[m_merkle_first_leaf + index][0];
			}
			else
			{
				TORRENT_ASSERT(m_piece_hashes);
				TORRENT_ASSERT(m_piece_hashes >= m_info_section.get());
				TORRENT_ASSERT(m_piece_hashes < m_info_section.get() + m_info_section_size);
				TORRENT_ASSERT(index < m_info_section_size / 20);
				return &m_piece_hashes[index*20];
			}
		}

		boost::optional<pt::ptime> creation_date() const;

		const std::string& creator() const
		{ return m_created_by; }

		const std::string& comment() const
		{ return m_comment; }

		// dht nodes to add to the routing table/bootstrap from
		typedef std::vector<std::pair<std::string, int> > nodes_t;

		nodes_t const& nodes() const
		{ return m_nodes; }
		void add_node(std::pair<std::string, int> const& node)
		{ m_nodes.push_back(node); }

		bool parse_info_section(lazy_entry const& e, error_code& ex);

		lazy_entry const* info(char const* key) const
		{
			if (m_info_dict.type() == lazy_entry::none_t)
				lazy_bdecode(m_info_section.get(), m_info_section.get()
					+ m_info_section_size, m_info_dict);
			return m_info_dict.dict_find(key);
		}

		void swap(torrent_info& ti);

		boost::shared_array<char> metadata() const
		{ return m_info_section; }

		int metadata_size() const { return m_info_section_size; }

		bool add_merkle_nodes(std::map<int, sha1_hash> const& subtree
			, int piece);
		std::map<int, sha1_hash> build_merkle_list(int piece) const;
		bool is_merkle_torrent() const { return !m_merkle_tree.empty(); }

	private:

		void copy_on_write();
		bool parse_torrent_file(lazy_entry const& libtorrent, error_code& ec);

		file_storage m_files;

		// if m_files is modified, it is first copied into
		// m_orig_files so that the original name and
		// filenames are preserved.
		boost::shared_ptr<const file_storage> m_orig_files;

		// the urls to the trackers
		std::vector<announce_entry> m_urls;
		std::vector<std::string> m_url_seeds;
		std::vector<std::string> m_http_seeds;
		nodes_t m_nodes;

		// the hash that identifies this torrent
		sha1_hash m_info_hash;

		// if a creation date is found in the torrent file
		// this will be set to that, otherwise it'll be
		// 1970, Jan 1
		pt::ptime m_creation_date;

		// if a comment is found in the torrent file
		// this will be set to that comment
		std::string m_comment;

		// an optional string naming the software used
		// to create the torrent file
		std::string m_created_by;

		// this is used when creating a torrent. If there's
		// only one file there are cases where it's impossible
		// to know if it should be written as a multifile torrent
		// or not. e.g. test/test  there's one file and one directory
		// and they have the same name.
		bool m_multifile;

		// this is true if the torrent is private. i.e., is should not
		// be announced on the dht
		bool m_private;

		// this is a copy of the info section from the torrent.
		// it use maintained in this flat format in order to
		// make it available through the metadata extension
		boost::shared_array<char> m_info_section;
		int m_info_section_size;

		// this is a pointer into the m_info_section buffer
		// pointing to the first byte of the first sha-1 hash
		char const* m_piece_hashes;

		// if this is a merkle torrent, this is the merkle
		// tree. It has space for merkle_num_nodes(merkle_num_leafs(num_pieces))
		// hashes
		std::vector<sha1_hash> m_merkle_tree;
		// the index to the first leaf. This is where the hash for the
		// first piece is stored
		int m_merkle_first_leaf;

		// the info section parsed. points into m_info_section
		// parsed lazily
		mutable lazy_entry m_info_dict;
	};

}

#endif // TORRENT_TORRENT_INFO_HPP_INCLUDED

<commit_msg>remove iostream dependency<commit_after>/*

Copyright (c) 2003-2008, 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_TORRENT_INFO_HPP_INCLUDED
#define TORRENT_TORRENT_INFO_HPP_INCLUDED

#include <string>
#include <vector>
//#include <iosfwd>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/optional.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/shared_array.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/entry.hpp"
#include "libtorrent/lazy_entry.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/peer_id.hpp"
#include "libtorrent/size_type.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/time.hpp"
#include "libtorrent/intrusive_ptr_base.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/file_storage.hpp"

namespace libtorrent
{
	namespace pt = boost::posix_time;
	namespace gr = boost::gregorian;
	namespace fs = boost::filesystem;

	enum
	{
		// wait 60 seconds before retrying a failed tracker
		tracker_retry_delay_min = 10
		// when tracker_failed_max trackers
		// has failed, wait 60 minutes instead
		, tracker_retry_delay_max = 60 * 60
	};

	struct TORRENT_EXPORT announce_entry
	{
		announce_entry(std::string const& u)
			: url(u)
			, tier(0)
			, fail_limit(3)
			, fails(0)
			, source(0)
			, verified(false)
			, updating(false)
			, start_sent(false)
			, complete_sent(false)
		{}

		std::string url;

		// the time of next tracker announce
		ptime next_announce;

		boost::uint8_t tier;
		// the number of times this tracker can fail
		// in a row before it's removed. 0 means unlimited
		boost::uint8_t fail_limit;

		// the number of times in a row this tracker has failed
		boost::uint8_t fails;

		enum tracker_source
		{
			source_torrent = 1,
			source_client = 2,
			source_magnet_link = 4,
			source_tex = 8
		};
		// where did we get this tracker from
		boost::uint8_t source;

		// is set to true if we have ever received a response from
		// this tracker
		bool verified:1;

		// true if we're currently trying to announce with
		// this tracker
		bool updating:1;

		// this is true if event start has been sent to the tracker
		bool start_sent:1;

		// this is true if event completed has been sent to the tracker
		bool complete_sent:1;

		void reset()
		{
			start_sent = false;
			next_announce = min_time();
		}

		void failed()
		{
			++fails;
			int delay = (std::min)(tracker_retry_delay_min + int(fails) * int(fails) * tracker_retry_delay_min
				, int(tracker_retry_delay_max));
			next_announce = time_now() + seconds(delay);
			updating = false;
		}

		bool can_announce(ptime now) const
		{
			return now >= next_announce
				&& (fails < fail_limit || fail_limit == 0)
				&& !updating;
		}

		bool is_working() const
		{
			return fails == 0;
		}
	};

#ifndef BOOST_NO_EXCEPTIONS
	// for backwards compatibility with 0.14
	typedef libtorrent_exception invalid_torrent_file;
#endif

	int TORRENT_EXPORT load_file(fs::path const& filename, std::vector<char>& v);

	class TORRENT_EXPORT torrent_info : public intrusive_ptr_base<torrent_info>
	{
	public:
#ifndef BOOST_NO_EXCEPTIONS
		torrent_info(lazy_entry const& torrent_file);
		torrent_info(char const* buffer, int size);
		torrent_info(fs::path const& filename);
#ifndef BOOST_FILESYSTEM_NARROW_ONLY
		torrent_info(fs::wpath const& filename);
#endif
#endif

		torrent_info(sha1_hash const& info_hash);
		torrent_info(lazy_entry const& torrent_file, error_code& ec);
		torrent_info(char const* buffer, int size, error_code& ec);
		torrent_info(fs::path const& filename, error_code& ec);
#ifndef BOOST_FILESYSTEM_NARROW_ONLY
		torrent_info(fs::wpath const& filename, error_code& ec);
#endif

		~torrent_info();

		file_storage const& files() const { return m_files; }
		file_storage const& orig_files() const { return m_orig_files ? *m_orig_files : m_files; }

		void rename_file(int index, std::string const& new_filename)
		{
			copy_on_write();
			m_files.rename_file(index, new_filename);
		}

#ifndef BOOST_FILESYSTEM_NARROW_ONLY
		void rename_file(int index, std::wstring const& new_filename)
		{
			copy_on_write();
			m_files.rename_file(index, new_filename);
		}
#endif

		void add_tracker(std::string const& url, int tier = 0);
		std::vector<announce_entry> const& trackers() const { return m_urls; }

		std::vector<std::string> const& url_seeds() const
		{ return m_url_seeds; }
		void add_url_seed(std::string const& url)
		{ m_url_seeds.push_back(url); }

		std::vector<std::string> const& http_seeds() const
		{ return m_http_seeds; }
		void add_http_seed(std::string const& url)
		{ m_http_seeds.push_back(url); }

		size_type total_size() const { return m_files.total_size(); }
		int piece_length() const { return m_files.piece_length(); }
		int num_pieces() const { return m_files.num_pieces(); }
		const sha1_hash& info_hash() const { return m_info_hash; }
		const std::string& name() const { return m_files.name(); }

		typedef file_storage::iterator file_iterator;
		typedef file_storage::reverse_iterator reverse_file_iterator;

		file_iterator begin_files() const { return m_files.begin(); }
		file_iterator end_files() const { return m_files.end(); }
		reverse_file_iterator rbegin_files() const { return m_files.rbegin(); }
		reverse_file_iterator rend_files() const { return m_files.rend(); }
		int num_files() const { return m_files.num_files(); }
		file_entry const& file_at(int index) const { return m_files.at(index); }

		file_iterator file_at_offset(size_type offset) const
		{ return m_files.file_at_offset(offset); }
		std::vector<file_slice> map_block(int piece, size_type offset, int size) const
		{ return m_files.map_block(piece, offset, size); }
		peer_request map_file(int file, size_type offset, int size) const
		{ return m_files.map_file(file, offset, size); }

#ifndef TORRENT_NO_DEPRECATE
// ------- start deprecation -------
// these functions will be removed in a future version
		torrent_info(entry const& torrent_file) TORRENT_DEPRECATED;
		void print(std::ostream& os) const TORRENT_DEPRECATED;
// ------- end deprecation -------
#endif

		bool is_valid() const { return m_files.is_valid(); }

		bool priv() const { return m_private; }

		int piece_size(int index) const { return m_files.piece_size(index); }

		sha1_hash hash_for_piece(int index) const
		{ return sha1_hash(hash_for_piece_ptr(index)); }

		std::vector<sha1_hash> const& merkle_tree() const { return m_merkle_tree; }
		void set_merkle_tree(std::vector<sha1_hash>& h)
		{ TORRENT_ASSERT(h.size() == m_merkle_tree.size() ); m_merkle_tree.swap(h); }

		char const* hash_for_piece_ptr(int index) const
		{
			TORRENT_ASSERT(index >= 0);
			TORRENT_ASSERT(index < m_files.num_pieces());
			if (is_merkle_torrent())
			{
				TORRENT_ASSERT(index < int(m_merkle_tree.size()) - m_merkle_first_leaf);
				return (const char*)&m_merkle_tree[m_merkle_first_leaf + index][0];
			}
			else
			{
				TORRENT_ASSERT(m_piece_hashes);
				TORRENT_ASSERT(m_piece_hashes >= m_info_section.get());
				TORRENT_ASSERT(m_piece_hashes < m_info_section.get() + m_info_section_size);
				TORRENT_ASSERT(index < m_info_section_size / 20);
				return &m_piece_hashes[index*20];
			}
		}

		boost::optional<pt::ptime> creation_date() const;

		const std::string& creator() const
		{ return m_created_by; }

		const std::string& comment() const
		{ return m_comment; }

		// dht nodes to add to the routing table/bootstrap from
		typedef std::vector<std::pair<std::string, int> > nodes_t;

		nodes_t const& nodes() const
		{ return m_nodes; }
		void add_node(std::pair<std::string, int> const& node)
		{ m_nodes.push_back(node); }

		bool parse_info_section(lazy_entry const& e, error_code& ex);

		lazy_entry const* info(char const* key) const
		{
			if (m_info_dict.type() == lazy_entry::none_t)
				lazy_bdecode(m_info_section.get(), m_info_section.get()
					+ m_info_section_size, m_info_dict);
			return m_info_dict.dict_find(key);
		}

		void swap(torrent_info& ti);

		boost::shared_array<char> metadata() const
		{ return m_info_section; }

		int metadata_size() const { return m_info_section_size; }

		bool add_merkle_nodes(std::map<int, sha1_hash> const& subtree
			, int piece);
		std::map<int, sha1_hash> build_merkle_list(int piece) const;
		bool is_merkle_torrent() const { return !m_merkle_tree.empty(); }

	private:

		void copy_on_write();
		bool parse_torrent_file(lazy_entry const& libtorrent, error_code& ec);

		file_storage m_files;

		// if m_files is modified, it is first copied into
		// m_orig_files so that the original name and
		// filenames are preserved.
		boost::shared_ptr<const file_storage> m_orig_files;

		// the urls to the trackers
		std::vector<announce_entry> m_urls;
		std::vector<std::string> m_url_seeds;
		std::vector<std::string> m_http_seeds;
		nodes_t m_nodes;

		// the hash that identifies this torrent
		sha1_hash m_info_hash;

		// if a creation date is found in the torrent file
		// this will be set to that, otherwise it'll be
		// 1970, Jan 1
		pt::ptime m_creation_date;

		// if a comment is found in the torrent file
		// this will be set to that comment
		std::string m_comment;

		// an optional string naming the software used
		// to create the torrent file
		std::string m_created_by;

		// this is used when creating a torrent. If there's
		// only one file there are cases where it's impossible
		// to know if it should be written as a multifile torrent
		// or not. e.g. test/test  there's one file and one directory
		// and they have the same name.
		bool m_multifile;

		// this is true if the torrent is private. i.e., is should not
		// be announced on the dht
		bool m_private;

		// this is a copy of the info section from the torrent.
		// it use maintained in this flat format in order to
		// make it available through the metadata extension
		boost::shared_array<char> m_info_section;
		int m_info_section_size;

		// this is a pointer into the m_info_section buffer
		// pointing to the first byte of the first sha-1 hash
		char const* m_piece_hashes;

		// if this is a merkle torrent, this is the merkle
		// tree. It has space for merkle_num_nodes(merkle_num_leafs(num_pieces))
		// hashes
		std::vector<sha1_hash> m_merkle_tree;
		// the index to the first leaf. This is where the hash for the
		// first piece is stored
		int m_merkle_first_leaf;

		// the info section parsed. points into m_info_section
		// parsed lazily
		mutable lazy_entry m_info_dict;
	};

}

#endif // TORRENT_TORRENT_INFO_HPP_INCLUDED

<|endoftext|>


<commit_before>#ifndef PROTON_UT_H
#define PROTON_UT_H

#include <vector>

namespace proton{
namespace detail{

/////////////////////////////
// unittest

//@return 0 - success
typedef int (*unittest_t)();

/** a lite unit test framework.
 * @param ut unit tests need to be tested.
 * @return 0: succes, other: failure
 */
int unittest_run(std::vector<unittest_t>& ut);

}}
#endif // PROTON_UT_H
<commit_msg>add remark for ut<commit_after>#ifndef PROTON_UT_H
#define PROTON_UT_H

/** @file unit_test.hpp
 *  @brief a lite unit test framework.
 */

#include <vector>

namespace proton{
namespace detail{

/////////////////////////////
// unittest

//@return 0 - success
typedef int (*unittest_t)();

/** a lite unit test framework.
 * @param ut unit tests need to be tested.
 * @return 0: succes, other: failure
 */
int unittest_run(std::vector<unittest_t>& ut);

}}
#endif // PROTON_UT_H
<|endoftext|>


<commit_before>#ifndef SIPLASPLAS_UTILITY_HASH_HPP
#define SIPLASPLAS_UTILITY_HASH_HPP

#include "tuple.hpp"
#include "function_traits.hpp"

#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <memory>
#include <cstring>

namespace cpp
{

template<typename T>
constexpr std::size_t hash(const T& value);
template<typename T, typename U, typename... Args>
constexpr std::size_t hash(const T& first, const U& second, const Args&... tail);
template<typename T>
std::size_t raw_hash(const T& value);

namespace
{

template<typename T, cpp::FunctionKind Kind = cpp::function_kind<T>()>
class HashDispatch
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return std::hash<T>{}(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::FREE_FUNCTION>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return ::cpp::raw_hash(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::MEMBER_FUNCTION>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return ::cpp::raw_hash(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::CONST_MEMBER_FUNCTION>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return ::cpp::raw_hash(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::FUNCTOR>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        if(std::is_empty<T>::value)
        {
            return ::cpp::hash(&T::operator());
        }
        else
        {
            return ::cpp::hash(&value, &T::operator());
        }
    }
};

}

template<typename T>
constexpr std::size_t hash_combine(std::size_t seed, const T& value)
{
    std::hash<T> hasher;

    return seed ^ (hasher(value) + 0x9e3779b9 + (seed<<6) + (seed>>2));
}

template<typename T>
constexpr std::size_t hash(const T& value)
{
    return HashDispatch<T>::apply(value);
}

template<typename T, typename U, typename... Args>
constexpr std::size_t hash(const T& first, const U& second, const Args&... tail)
{
    return hash_combine(
        hash(first),
        hash(second, tail...)
    );
}

template<typename T, typename U>
constexpr std::size_t hash(const std::pair<T, U>& pair)
{
    return hash(pair.first, pair.second);
}

template<typename... Ts>
constexpr std::size_t hash(const std::tuple<Ts...>& tuple)
{
    return cpp::tuple_call(
        tuple,
        [](const Ts&... args)
        {
            return hash(args...);
        }
    );
}

template<typename T>
struct Hash
{
public:
    constexpr std::size_t operator()(const T& value) const
    {
        return ::cpp::hash(value);
    }
};

template<typename Key, typename Value>
using HashTable = std::unordered_map<Key, Value, Hash<Key>>;
template<typename Key>
using HashSet = std::unordered_set<Key, Hash<Key>>;

template<typename T>
std::size_t raw_hash(const T& value)
{
    std::aligned_storage_t<sizeof(T), alignof(T)> rawStorage;
    std::memcpy(&rawStorage, &value, sizeof(T));
    std::size_t hash = 0;

    for(std::size_t i = 0; i < sizeof(T); ++i)
    {
        hash = hash_combine(hash, reinterpret_cast<const char*>(&rawStorage)[i]);
    }

    return hash;
}

template<typename T>
class RawHash
{
public:
    constexpr std::size_t operator()(const T& value) const
    {
        return raw_hash(value);
    }
};

}

#endif // SIPLASPLAS_UTILITY_HASH_HPP
<commit_msg>hash docs<commit_after>#ifndef SIPLASPLAS_UTILITY_HASH_HPP
#define SIPLASPLAS_UTILITY_HASH_HPP

#include "tuple.hpp"
#include "function_traits.hpp"

#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <memory>
#include <cstring>

/**
 * \defgroup hash
 * \ingroup utility
 * \brief Hashing utilities based on `std::hash`.
 *
 * This implements the following hashing tools:
 *
 *  - **Free hash function**: A cpp::hash() free function template for simple
 *  hash code retrieval. Because `std::hash<int>()(42)` is horrible.
 *  - **Hash combination**: cpp::hash() is really a variadic template function that implements
 *  pairwise hash combination.
 *  - **Improved hash functor**: cpp::Hash implements a hash functor for maps that wraps
 *  cpp::hash() functionallity. The extended functionallity of cpp::Hash over `std::hash`
 *  includes hashing of enum types, pairs, and tuples out of the box.
 *  - **Hashing of function pointers**: Because we love undefined behavior!
 */

namespace cpp
{

/**
 * \ingroup hash
 * \brief Implements a hash function for values of type T.
 *
 * \param value Value to compute the hash code.
 *
 * \return For enumeration types returns the hash of the underlying integral value.
 * For function types returns a bytewise hash of the function object (See cpp::raw_hash()).
 * For tuple and pair types returns a hash combination of all tuple elements (See cpp::hash_combine() and
 * n-ary cpp::hash() overload).
 * Otherwise returns the value given by `std::hash<T>`.
 */
template<typename T>
constexpr std::size_t hash(const T& value);

/**
 * \ingroup hash
 * \brief Returns the comination of hashes of a set of values.
 *
 * This function is a generalization of unary cpp::hash() that accepts two or more input
 * values. The resulting hash code is computed as the hash combination (See cpp::hash_combine())
 * of the first value and the hash combination of the rest:
 *
 * ``` haskell
 * hash first:second:tail -> hash_combine (hash first) (hash second:tail)
 * ```
 *
 * \param values A variadic pack of at least two elements. These are the values
 * to get the combined hash code.
 *
 * \return Pairwise hash combination of the values. The hash of each value is computed by cpp::hash().
 */
template<typename T, typename U, typename... Args>
constexpr std::size_t hash(const T& first, const U& second, const Args&... tail);

/**
 * \ingroup hash
 * \brief Returns a bytewise hash of a given value.
 *
 * This function ignores the `std::hash` specialization of the value type and implements
 * a bytewise hash value instead. Bytewise hash is computed as a hash combination of each byte
 * of the value storage, in the range `[addressof(value), addressof(value) + sizeof(T))`. The
 * value is copyed to an intermediary aligned storage to perform the byte traversal.
 *
 * \return A value equivalent to `cpp::hash(<bytes of value>...)`.
 */
template<typename T>
std::size_t raw_hash(const T& value);

namespace
{

template<typename T, cpp::FunctionKind Kind = cpp::function_kind<T>()>
class HashDispatch
{
public:
    template<typename U, typename = void>
    class HashDispatchForValueTypes
    {
    public:
        static constexpr std::size_t apply(const U& value)
        {
            return std::hash<T>{}(value);
        }
    };

    template<typename U>
    class HashDispatchForValueTypes<U, typename std::enable_if<std::is_enum<U>::value>::type>
    {
    public:
        static constexpr std::size_t apply(const U& value)
        {
            return std::hash<T>{}(static_cast<typename std::underlying_type<U>::type>(value));
        }
    };

    static constexpr std::size_t apply(const T& value)
    {
        return HashDispatchForValueTypes<T>::apply(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::FREE_FUNCTION>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return ::cpp::raw_hash(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::MEMBER_FUNCTION>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return ::cpp::raw_hash(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::CONST_MEMBER_FUNCTION>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        return ::cpp::raw_hash(value);
    }
};

template<typename T>
class HashDispatch<T, cpp::FunctionKind::FUNCTOR>
{
public:
    static constexpr std::size_t apply(const T& value)
    {
        if(std::is_empty<T>::value)
        {
            return ::cpp::hash(&T::operator());
        }
        else
        {
            return ::cpp::hash(&value, &T::operator());
        }
    }
};

}

/**
 * \ingroup hash
 * \brief Implements a hash combination function of a given hash value and a value of type T.
 *
 * Literally copied from [this stack overflow thread](http://stackoverflow.com/questions/7110301/generic-hash-for-tuples-in-unordered-map-unordered-set)
 * which in turn got it from [`boost::hash_combine()`](http://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html).
 *
 * \param seed Source hash value to combine.
 * \param value Value of type T wich has will be combined.
 * \return the combination between the seed value and the hash of the input value. See `boost::hash_combine()` link
 * above for the specific combination function.
 */
template<typename T>
constexpr std::size_t hash_combine(std::size_t seed, const T& value)
{
    return seed ^ (hash(value) + 0x9e3779b9 + (seed<<6) + (seed>>2));
}

template<typename T>
constexpr std::size_t hash(const T& value)
{
    return HashDispatch<T>::apply(value);
}

template<typename T, typename U, typename... Args>
constexpr std::size_t hash(const T& first, const U& second, const Args&... tail)
{
    return hash_combine(
        hash(first),
        hash(second, tail...)
    );
}

template<typename T, typename U>
constexpr std::size_t hash(const std::pair<T, U>& pair)
{
    return hash(pair.first, pair.second);
}

template<typename... Ts>
constexpr std::size_t hash(const std::tuple<Ts...>& tuple)
{
    return cpp::tuple_call(
        tuple,
        [](const Ts&... args)
        {
            return hash(args...);
        }
    );
}

/**
 * \ingroup hash
 * \brief A functor that implements a hash function for values of type T.
 *
 * This template provides the features of cpp::hash() as a functor template,
 * suitable for unordered containers.
 *
 * \tparam T Type of the values to get the hash code. See cpp::hash() for behavior and type
 * requirements.
 */
template<typename T>
struct Hash
{
public:
    constexpr std::size_t operator()(const T& value) const
    {
        return ::cpp::hash(value);
    }
};

/**
 * \ingroup hash
 * \brief `std::unordered_map` alias using cpp::Hash as hash.
 *
 * \tparam Key Key type.
 * \tparam Value Value type.
 */
template<typename Key, typename Value>
using HashTable = std::unordered_map<Key, Value, Hash<Key>>;

/**
 * \ingroup hash
 * \brief `std::set` alias using cpp::Hash as hash.
 *
 * \tparam Key Key type.
 */
template<typename Key>
using HashSet = std::unordered_set<Key, Hash<Key>>;

template<typename T>
std::size_t raw_hash(const T& value)
{
    std::aligned_storage_t<sizeof(T), alignof(T)> rawStorage;
    std::memcpy(&rawStorage, &value, sizeof(T));
    std::size_t hash = 0;

    for(std::size_t i = 0; i < sizeof(T); ++i)
    {
        hash = hash_combine(hash, reinterpret_cast<const char*>(&rawStorage)[i]);
    }

    return hash;
}

/**
 * \ingroup hash
 * \brief A functor that implements a bytewise hash function for values of type T.
 *
 * This template provides the features of cpp::raw_hash() as a functor template,
 * suitable for unordered containers.
 *
 * \tparam T Type of the values to get the hash code. See cpp::raw_hash() for behavior and type
 * requirements.
 */
template<typename T>
class RawHash
{
public:
    constexpr std::size_t operator()(const T& value) const
    {
        return raw_hash(value);
    }
};

}

#endif // SIPLASPLAS_UTILITY_HASH_HPP
<|endoftext|>


<commit_before>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.

#include "libEGL/Surface.h"

#include "common/debug.h"

#include "libEGL/main.h"
#include "libEGL/Display.h"

namespace egl
{
Surface::Surface(Display *display, const Config *config, HWND window)
    : mDisplay(display), mConfig(config), mWindow(window)
{
    mSwapChain = NULL;
    mDepthStencil = NULL;
    mBackBuffer = NULL;
    mRenderTarget = NULL;
    mFlipTexture = NULL;
    mFlipState = NULL;
    mPreFlipState = NULL;

    mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING);   // FIXME: Determine actual pixel aspect ratio
    mRenderBuffer = EGL_BACK_BUFFER;
    mSwapBehavior = EGL_BUFFER_PRESERVED;

    resetSwapChain();
}

Surface::~Surface()
{
    if (mSwapChain)
    {
        mSwapChain->Release();
    }

    if (mBackBuffer)
    {
        mBackBuffer->Release();
    }

    if (mRenderTarget)
    {
        mRenderTarget->Release();
    }

    if (mDepthStencil)
    {
        mDepthStencil->Release();
    }

    if (mFlipTexture)
    {
        mFlipTexture->Release();
    }

    if (mFlipState)
    {
        mFlipState->Release();
    }

    if (mPreFlipState)
    {
        mPreFlipState->Release();
    }
}

void Surface::resetSwapChain()
{
    IDirect3DDevice9 *device = mDisplay->getDevice();

    D3DPRESENT_PARAMETERS presentParameters = {0};

    presentParameters.AutoDepthStencilFormat = mConfig->mDepthStencilFormat;
    presentParameters.BackBufferCount = 1;
    presentParameters.BackBufferFormat = mConfig->mRenderTargetFormat;
    presentParameters.EnableAutoDepthStencil = FALSE;
    presentParameters.Flags = 0;
    presentParameters.hDeviceWindow = getWindowHandle();
    presentParameters.MultiSampleQuality = 0;                  // FIXME: Unimplemented
    presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;   // FIXME: Unimplemented
    presentParameters.PresentationInterval = Display::convertInterval(mConfig->mMinSwapInterval);
    presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
    presentParameters.Windowed = TRUE;

    RECT windowRect;
    GetClientRect(getWindowHandle(), &windowRect);
    presentParameters.BackBufferWidth = windowRect.right - windowRect.left;
    presentParameters.BackBufferHeight = windowRect.bottom - windowRect.top;

    IDirect3DSwapChain9 *swapChain = NULL;
    HRESULT result = device->CreateAdditionalSwapChain(&presentParameters, &swapChain);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        ERR("Could not create additional swap chains: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    IDirect3DSurface9 *depthStencilSurface = NULL;
    result = device->CreateDepthStencilSurface(presentParameters.BackBufferWidth, presentParameters.BackBufferHeight,
                                               presentParameters.AutoDepthStencilFormat, presentParameters.MultiSampleType,
                                               presentParameters.MultiSampleQuality, FALSE, &depthStencilSurface, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        swapChain->Release();

        ERR("Could not create depthstencil surface for new swap chain: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    IDirect3DSurface9 *renderTarget = NULL;
    result = device->CreateRenderTarget(presentParameters.BackBufferWidth, presentParameters.BackBufferHeight, presentParameters.BackBufferFormat,
                                        presentParameters.MultiSampleType, presentParameters.MultiSampleQuality, FALSE, &renderTarget, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        swapChain->Release();
        depthStencilSurface->Release();

        ERR("Could not create render target surface for new swap chain: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    ASSERT(SUCCEEDED(result));

    IDirect3DTexture9 *flipTexture = NULL;
    result = device->CreateTexture(presentParameters.BackBufferWidth, presentParameters.BackBufferHeight, 1, D3DUSAGE_RENDERTARGET,
                                   presentParameters.BackBufferFormat, D3DPOOL_DEFAULT, &flipTexture, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        swapChain->Release();
        depthStencilSurface->Release();
        renderTarget->Release();

        ERR("Could not create flip texture for new swap chain: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    IDirect3DSurface9 *backBuffer = NULL;
    swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);

    if (mSwapChain) mSwapChain->Release();
    if (mDepthStencil) mDepthStencil->Release();
    if (mBackBuffer) mBackBuffer->Release();
    if (mRenderTarget) mRenderTarget->Release();
    if (mFlipTexture) mFlipTexture->Release();

    mWidth = presentParameters.BackBufferWidth;
    mHeight = presentParameters.BackBufferHeight;

    mSwapChain = swapChain;
    mDepthStencil = depthStencilSurface;
    mBackBuffer = backBuffer;
    mRenderTarget = renderTarget;
    mFlipTexture = flipTexture;

    // The flip state block recorded mFlipTexture so it is now invalid.
    releaseRecordedState(device);
}

HWND Surface::getWindowHandle()
{
    return mWindow;
}

void Surface::writeRecordableFlipState(IDirect3DDevice9 *device)
{
    // Disable all pipeline operations
    device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
    device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
    device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
    device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
    device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
    device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
    device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
    device->SetPixelShader(NULL);
    device->SetVertexShader(NULL);

    // Just sample the texture
    device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
    device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
    device->SetTexture(0, NULL); // The actual texture will change after resizing. But the pre-flip state block must save/restore the texture.
    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, FALSE);
    device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
    device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
    device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);

    device->SetStreamSourceFreq(0, 1); // DrawPrimitiveUP only cares about stream 0, not the rest.
}

void Surface::applyFlipState(IDirect3DDevice9 *device)
{
    HRESULT hr;

    if (mFlipState == NULL)
    {
        // Create two state blocks both recording the states that are changed when swapping.

        // mPreFlipState will record the original state each entry.
        hr = device->BeginStateBlock();
        ASSERT(SUCCEEDED(hr));
        writeRecordableFlipState(device);
        hr = device->EndStateBlock(&mPreFlipState);
        ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);

        if (SUCCEEDED(hr))
        {
            mPreFlipState->Capture();
        }

        // mFlipState will record the state for the swap operation.
        hr = device->BeginStateBlock();
        ASSERT(SUCCEEDED(hr));

        writeRecordableFlipState(device);

        hr = device->EndStateBlock(&mFlipState);
        ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);

        if (FAILED(hr))
        {
            mFlipState = NULL;
            mPreFlipState->Release();
            mPreFlipState = NULL;
        }
        else
        {
            hr = mFlipState->Apply();
            ASSERT(SUCCEEDED(hr));
        }
    }
    else
    {
        hr = mPreFlipState->Capture();
        ASSERT(SUCCEEDED(hr));
        hr = mFlipState->Apply();
        ASSERT(SUCCEEDED(hr));
    }

    device->GetRenderTarget(0, &mPreFlipBackBuffer);
    device->GetDepthStencilSurface(&mPreFlipDepthStencil);

    device->SetRenderTarget(0, mBackBuffer);
    device->SetDepthStencilSurface(NULL);
}

void Surface::restoreState(IDirect3DDevice9 *device)
{
    mPreFlipState->Apply();

    device->SetRenderTarget(0, mPreFlipBackBuffer);
    device->SetDepthStencilSurface(mPreFlipDepthStencil);

    if (mPreFlipBackBuffer)
    {
        mPreFlipBackBuffer->Release();
        mPreFlipBackBuffer = NULL;
    }

    if (mPreFlipDepthStencil)
    {
        mPreFlipDepthStencil->Release();
        mPreFlipDepthStencil = NULL;
    }
}

// On the next flip, this will cause the state to be recorded from scratch.
// In particular we need to do this if the flip texture changes.
void Surface::releaseRecordedState(IDirect3DDevice9 *device)
{
    if (mFlipState)
    {
        mFlipState->Release();
        mFlipState = NULL;
    }

    if (mPreFlipState)
    {
        mPreFlipState->Release();
        mPreFlipState = NULL;
    }
}

bool Surface::checkForWindowResize()
{
    RECT client;
    GetClientRect(getWindowHandle(), &client);
    if (getWidth() != client.right - client.left || getHeight() != client.bottom - client.top)
    {
        resetSwapChain();

        if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
        {
            glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
        }

        return true;
    }

    return false;
}

bool Surface::swap()
{
    if (mSwapChain)
    {
        IDirect3DTexture9 *flipTexture = mFlipTexture;
        flipTexture->AddRef();

        IDirect3DSurface9 *renderTarget = mRenderTarget;
        renderTarget->AddRef();

        EGLint oldWidth = mWidth;
        EGLint oldHeight = mHeight;

        checkForWindowResize();

        IDirect3DDevice9 *device = mDisplay->getDevice();

        IDirect3DSurface9 *textureSurface;
        flipTexture->GetSurfaceLevel(0, &textureSurface);

        mDisplay->endScene();
        device->StretchRect(renderTarget, NULL, textureSurface, NULL, D3DTEXF_NONE);
        renderTarget->Release();

        applyFlipState(device);
        device->SetTexture(0, flipTexture);

        float xscale = (float)mWidth / oldWidth;
        float yscale = (float)mHeight / oldHeight;

        // Render the texture upside down into the back buffer
        // Texcoords are chosen to pin a potentially resized image into the upper-left corner without scaling.
        float quad[4][6] = {{     0 - 0.5f,       0 - 0.5f, 0.0f, 1.0f, 0.0f,   1.0f       },
                            {mWidth - 0.5f,       0 - 0.5f, 0.0f, 1.0f, xscale, 1.0f       },
                            {mWidth - 0.5f, mHeight - 0.5f, 0.0f, 1.0f, xscale, 1.0f-yscale},
                            {     0 - 0.5f, mHeight - 0.5f, 0.0f, 1.0f, 0.0f,   1.0f-yscale}};   // x, y, z, rhw, u, v

        mDisplay->startScene();
        device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));

        flipTexture->Release();
        textureSurface->Release();

        restoreState(device);

        mDisplay->endScene();
        HRESULT result = mSwapChain->Present(NULL, NULL, NULL, NULL, mDisplay->getPresentInterval());

        if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
        {
            return error(EGL_BAD_ALLOC, false);
        }

        if (result == D3DERR_DEVICELOST)
        {
            return error(EGL_CONTEXT_LOST, false);
        }

        ASSERT(SUCCEEDED(result));

    }

    return true;
}

EGLint Surface::getWidth() const
{
    return mWidth;
}

EGLint Surface::getHeight() const
{
    return mHeight;
}

IDirect3DSurface9 *Surface::getRenderTarget()
{
    if (mRenderTarget)
    {
        mRenderTarget->AddRef();
    }

    return mRenderTarget;
}

IDirect3DSurface9 *Surface::getDepthStencil()
{
    if (mDepthStencil)
    {
        mDepthStencil->AddRef();
    }

    return mDepthStencil;
}
}
<commit_msg>Added runtime checks for GetClientRect errors.<commit_after>//
// Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//

// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.

#include "libEGL/Surface.h"

#include "common/debug.h"

#include "libEGL/main.h"
#include "libEGL/Display.h"

namespace egl
{
Surface::Surface(Display *display, const Config *config, HWND window)
    : mDisplay(display), mConfig(config), mWindow(window)
{
    mSwapChain = NULL;
    mDepthStencil = NULL;
    mBackBuffer = NULL;
    mRenderTarget = NULL;
    mFlipTexture = NULL;
    mFlipState = NULL;
    mPreFlipState = NULL;

    mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING);   // FIXME: Determine actual pixel aspect ratio
    mRenderBuffer = EGL_BACK_BUFFER;
    mSwapBehavior = EGL_BUFFER_PRESERVED;

    resetSwapChain();
}

Surface::~Surface()
{
    if (mSwapChain)
    {
        mSwapChain->Release();
    }

    if (mBackBuffer)
    {
        mBackBuffer->Release();
    }

    if (mRenderTarget)
    {
        mRenderTarget->Release();
    }

    if (mDepthStencil)
    {
        mDepthStencil->Release();
    }

    if (mFlipTexture)
    {
        mFlipTexture->Release();
    }

    if (mFlipState)
    {
        mFlipState->Release();
    }

    if (mPreFlipState)
    {
        mPreFlipState->Release();
    }
}

void Surface::resetSwapChain()
{
    IDirect3DDevice9 *device = mDisplay->getDevice();

    D3DPRESENT_PARAMETERS presentParameters = {0};

    presentParameters.AutoDepthStencilFormat = mConfig->mDepthStencilFormat;
    presentParameters.BackBufferCount = 1;
    presentParameters.BackBufferFormat = mConfig->mRenderTargetFormat;
    presentParameters.EnableAutoDepthStencil = FALSE;
    presentParameters.Flags = 0;
    presentParameters.hDeviceWindow = getWindowHandle();
    presentParameters.MultiSampleQuality = 0;                  // FIXME: Unimplemented
    presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;   // FIXME: Unimplemented
    presentParameters.PresentationInterval = Display::convertInterval(mConfig->mMinSwapInterval);
    presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
    presentParameters.Windowed = TRUE;

    RECT windowRect;
    if (!GetClientRect(getWindowHandle(), &windowRect))
    {
        ASSERT(false);
        return;
    }

    presentParameters.BackBufferWidth = windowRect.right - windowRect.left;
    presentParameters.BackBufferHeight = windowRect.bottom - windowRect.top;

    IDirect3DSwapChain9 *swapChain = NULL;
    HRESULT result = device->CreateAdditionalSwapChain(&presentParameters, &swapChain);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        ERR("Could not create additional swap chains: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    IDirect3DSurface9 *depthStencilSurface = NULL;
    result = device->CreateDepthStencilSurface(presentParameters.BackBufferWidth, presentParameters.BackBufferHeight,
                                               presentParameters.AutoDepthStencilFormat, presentParameters.MultiSampleType,
                                               presentParameters.MultiSampleQuality, FALSE, &depthStencilSurface, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        swapChain->Release();

        ERR("Could not create depthstencil surface for new swap chain: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    IDirect3DSurface9 *renderTarget = NULL;
    result = device->CreateRenderTarget(presentParameters.BackBufferWidth, presentParameters.BackBufferHeight, presentParameters.BackBufferFormat,
                                        presentParameters.MultiSampleType, presentParameters.MultiSampleQuality, FALSE, &renderTarget, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        swapChain->Release();
        depthStencilSurface->Release();

        ERR("Could not create render target surface for new swap chain: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    ASSERT(SUCCEEDED(result));

    IDirect3DTexture9 *flipTexture = NULL;
    result = device->CreateTexture(presentParameters.BackBufferWidth, presentParameters.BackBufferHeight, 1, D3DUSAGE_RENDERTARGET,
                                   presentParameters.BackBufferFormat, D3DPOOL_DEFAULT, &flipTexture, NULL);

    if (FAILED(result))
    {
        ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);

        swapChain->Release();
        depthStencilSurface->Release();
        renderTarget->Release();

        ERR("Could not create flip texture for new swap chain: %08lX", result);
        return error(EGL_BAD_ALLOC);
    }

    IDirect3DSurface9 *backBuffer = NULL;
    swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &backBuffer);

    if (mSwapChain) mSwapChain->Release();
    if (mDepthStencil) mDepthStencil->Release();
    if (mBackBuffer) mBackBuffer->Release();
    if (mRenderTarget) mRenderTarget->Release();
    if (mFlipTexture) mFlipTexture->Release();

    mWidth = presentParameters.BackBufferWidth;
    mHeight = presentParameters.BackBufferHeight;

    mSwapChain = swapChain;
    mDepthStencil = depthStencilSurface;
    mBackBuffer = backBuffer;
    mRenderTarget = renderTarget;
    mFlipTexture = flipTexture;

    // The flip state block recorded mFlipTexture so it is now invalid.
    releaseRecordedState(device);
}

HWND Surface::getWindowHandle()
{
    return mWindow;
}

void Surface::writeRecordableFlipState(IDirect3DDevice9 *device)
{
    // Disable all pipeline operations
    device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
    device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
    device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
    device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
    device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
    device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
    device->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
    device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_RED);
    device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);
    device->SetPixelShader(NULL);
    device->SetVertexShader(NULL);

    // Just sample the texture
    device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
    device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
    device->SetTexture(0, NULL); // The actual texture will change after resizing. But the pre-flip state block must save/restore the texture.
    device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
    device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, FALSE);
    device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
    device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
    device->SetFVF(D3DFVF_XYZRHW | D3DFVF_TEX1);

    device->SetStreamSourceFreq(0, 1); // DrawPrimitiveUP only cares about stream 0, not the rest.
}

void Surface::applyFlipState(IDirect3DDevice9 *device)
{
    HRESULT hr;

    if (mFlipState == NULL)
    {
        // Create two state blocks both recording the states that are changed when swapping.

        // mPreFlipState will record the original state each entry.
        hr = device->BeginStateBlock();
        ASSERT(SUCCEEDED(hr));
        writeRecordableFlipState(device);
        hr = device->EndStateBlock(&mPreFlipState);
        ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);

        if (SUCCEEDED(hr))
        {
            mPreFlipState->Capture();
        }

        // mFlipState will record the state for the swap operation.
        hr = device->BeginStateBlock();
        ASSERT(SUCCEEDED(hr));

        writeRecordableFlipState(device);

        hr = device->EndStateBlock(&mFlipState);
        ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);

        if (FAILED(hr))
        {
            mFlipState = NULL;
            mPreFlipState->Release();
            mPreFlipState = NULL;
        }
        else
        {
            hr = mFlipState->Apply();
            ASSERT(SUCCEEDED(hr));
        }
    }
    else
    {
        hr = mPreFlipState->Capture();
        ASSERT(SUCCEEDED(hr));
        hr = mFlipState->Apply();
        ASSERT(SUCCEEDED(hr));
    }

    device->GetRenderTarget(0, &mPreFlipBackBuffer);
    device->GetDepthStencilSurface(&mPreFlipDepthStencil);

    device->SetRenderTarget(0, mBackBuffer);
    device->SetDepthStencilSurface(NULL);
}

void Surface::restoreState(IDirect3DDevice9 *device)
{
    mPreFlipState->Apply();

    device->SetRenderTarget(0, mPreFlipBackBuffer);
    device->SetDepthStencilSurface(mPreFlipDepthStencil);

    if (mPreFlipBackBuffer)
    {
        mPreFlipBackBuffer->Release();
        mPreFlipBackBuffer = NULL;
    }

    if (mPreFlipDepthStencil)
    {
        mPreFlipDepthStencil->Release();
        mPreFlipDepthStencil = NULL;
    }
}

// On the next flip, this will cause the state to be recorded from scratch.
// In particular we need to do this if the flip texture changes.
void Surface::releaseRecordedState(IDirect3DDevice9 *device)
{
    if (mFlipState)
    {
        mFlipState->Release();
        mFlipState = NULL;
    }

    if (mPreFlipState)
    {
        mPreFlipState->Release();
        mPreFlipState = NULL;
    }
}

bool Surface::checkForWindowResize()
{
    RECT client;
    if (!GetClientRect(getWindowHandle(), &client))
    {
        ASSERT(false);
        return false;
    }

    if (getWidth() != client.right - client.left || getHeight() != client.bottom - client.top)
    {
        resetSwapChain();

        if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
        {
            glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
        }

        return true;
    }

    return false;
}

bool Surface::swap()
{
    if (mSwapChain)
    {
        IDirect3DTexture9 *flipTexture = mFlipTexture;
        flipTexture->AddRef();

        IDirect3DSurface9 *renderTarget = mRenderTarget;
        renderTarget->AddRef();

        EGLint oldWidth = mWidth;
        EGLint oldHeight = mHeight;

        checkForWindowResize();

        IDirect3DDevice9 *device = mDisplay->getDevice();

        IDirect3DSurface9 *textureSurface;
        flipTexture->GetSurfaceLevel(0, &textureSurface);

        mDisplay->endScene();
        device->StretchRect(renderTarget, NULL, textureSurface, NULL, D3DTEXF_NONE);
        renderTarget->Release();

        applyFlipState(device);
        device->SetTexture(0, flipTexture);

        float xscale = (float)mWidth / oldWidth;
        float yscale = (float)mHeight / oldHeight;

        // Render the texture upside down into the back buffer
        // Texcoords are chosen to pin a potentially resized image into the upper-left corner without scaling.
        float quad[4][6] = {{     0 - 0.5f,       0 - 0.5f, 0.0f, 1.0f, 0.0f,   1.0f       },
                            {mWidth - 0.5f,       0 - 0.5f, 0.0f, 1.0f, xscale, 1.0f       },
                            {mWidth - 0.5f, mHeight - 0.5f, 0.0f, 1.0f, xscale, 1.0f-yscale},
                            {     0 - 0.5f, mHeight - 0.5f, 0.0f, 1.0f, 0.0f,   1.0f-yscale}};   // x, y, z, rhw, u, v

        mDisplay->startScene();
        device->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, quad, 6 * sizeof(float));

        flipTexture->Release();
        textureSurface->Release();

        restoreState(device);

        mDisplay->endScene();
        HRESULT result = mSwapChain->Present(NULL, NULL, NULL, NULL, mDisplay->getPresentInterval());

        if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DRIVERINTERNALERROR)
        {
            return error(EGL_BAD_ALLOC, false);
        }

        if (result == D3DERR_DEVICELOST)
        {
            return error(EGL_CONTEXT_LOST, false);
        }

        ASSERT(SUCCEEDED(result));

    }

    return true;
}

EGLint Surface::getWidth() const
{
    return mWidth;
}

EGLint Surface::getHeight() const
{
    return mHeight;
}

IDirect3DSurface9 *Surface::getRenderTarget()
{
    if (mRenderTarget)
    {
        mRenderTarget->AddRef();
    }

    return mRenderTarget;
}

IDirect3DSurface9 *Surface::getDepthStencil()
{
    if (mDepthStencil)
    {
        mDepthStencil->AddRef();
    }

    return mDepthStencil;
}
}
<|endoftext|>


<commit_before>/* author: Federico Tomasi
 * license: FreeBSD License
 * copyright: Copyright (C) 2016 Federico Tomasi
 */
#include <Python.h>
#include "libsvm_file.h"
#include "string_kernel.h"
#include "sum_string_kernel.h"
#include <sstream>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

// static PyArrayObject *
static PyObject *
sum_string_kernel(PyObject *self, PyObject *args, PyObject *keywds) {
    // Kernel parameters
    int normalize = 1;
    int verbose = 0;
    int save_output = 0;
    int return_float = 0;
    int hard_matching = 0;
    const int symbol_size = 255;  // A size of an alphabet
    const int max_length = 1000;  // A maximum sequence length
    int min_kn = 1;                   // A level of subsequence matching
    int max_kn = 2;                   // A level of subsequence matching
    double lambda = .5;          // A decay factor

    // Prepare data
    std::vector<std::string> vector_data;
    std::vector<std::string> vector_labels;

    Py_ssize_t list_size;      /* how many lines we passed for parsing */
    char * line;        /* pointer to the line as a string */

    PyObject * listObj; /* the list of strings */
    PyObject * strObj;  /* one string in the list */
    PyObject * labels = NULL; /* the list of strings */
    char * filename = (char *)"output.txt"; // default value

    static char *kwlist[] = {
        (char*)"sequences", (char*)"filename", (char*)"normalize",
        (char*)"min_kn", (char*)"max_kn", (char*)"lamda",
        (char*)"save_output", (char*)"hard_matching",
        (char*)"verbose", (char*)"return_float",
        (char*)"labels", NULL
    };
    /* the O! parses for a Python object (listObj) checked to be of type PyList_Type */
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!|siiidiiiiO!", kwlist,
            &PyList_Type, &listObj, &filename, &normalize, &min_kn, &max_kn,
            &lambda, &save_output, &hard_matching, &verbose, &return_float,
            &PyList_Type, &labels))
        return NULL;

    /* get the number of lines passed */
    list_size = PyList_Size(listObj);
    if (list_size < 0) return NULL; /* Not a list */

    std::string kernel_file(filename);
    std::string label;
    std::stringstream ss;
    for (Py_ssize_t i = 0; i < list_size; i++){
    	/* grab the string object from the next element of the list */
    	strObj = PyList_GetItem(listObj, i); /* Can't fail */
    	line = PyString_AsString(strObj);  /* make it a string */
        vector_data.push_back(line);

        if (labels != NULL) {
            strObj = PyList_GetItem(labels, i);
        	line = PyString_AsString(strObj);
            label = std::string(line);
        } else {
            // convert i into a string
            ss << i;
            label = ss.str();
        }
        vector_labels.push_back(label);
	}

    if(verbose) {
        std::cout << "Parameters:"
        << "\n\tfilename: " << filename
        << "\n\tnormalize: " << normalize
        << "\n\tmin_kn: " << min_kn
        << "\n\tmax_kn: " << max_kn
        << "\n\tlambda: " << lambda
        << "\n\thard_matching: " << hard_matching
        << std::endl;
    }

    if(min_kn > max_kn) {
        PyErr_SetString(PyExc_ValueError, "`min_kn` is higher than `max_kn`");
        return NULL;
    }

    // Main computations
    SumStringKernel<float> string_kernel(min_kn, max_kn, normalize,
                                         symbol_size, max_length, lambda,
                                         hard_matching);
    string_kernel.set_data(vector_data);
    string_kernel.compute_kernel();

    if (save_output) {
      if (!write_kernel(kernel_file, vector_labels, string_kernel)) {
        PyErr_SetString(PyExc_IOError, "Cannot write to filename specified");
        return NULL;
      }
    }

    if(return_float && list_size == 2) {
        return Py_BuildValue("f", string_kernel.values()[1]);
    }

    // build the numpy matrix to pass back to the Python code
    // need to copy data to prevent the deleting in string kernel class
    // TODO avoid copying data?
    float * data = (float*) malloc(list_size*list_size*sizeof(float));
    if (!data) {
        PyErr_SetString(PyExc_MemoryError, "out of memory");
        return NULL;
    }
    string_kernel.copy_kernel(data);

    npy_intp* size = (npy_intp*)malloc(sizeof(npy_intp)*2);
    size[0] = size[1] = list_size;
    PyObject * py_arr = PyArray_SimpleNewFromData(2, size, NPY_FLOAT, data);
    return py_arr;
}

static PyMethodDef StringKernelMethods[] = {
    {"sum_string_kernel", (PyCFunction)sum_string_kernel, METH_VARARGS | METH_KEYWORDS,
     "docs."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC initsum_string_kernel(void) {
    (void) Py_InitModule("sum_string_kernel", StringKernelMethods);
    import_array();  // required to use PyArray_SimpleNewFromData
}

int main(int argc, char *argv[]) {
    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(argv[0]);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Add a static module */
    initsum_string_kernel();
    return 0;
}
<commit_msg>add possibility to reduce min_kn with the length of the minimum string<commit_after>/* author: Federico Tomasi
 * license: FreeBSD License
 * copyright: Copyright (C) 2016 Federico Tomasi
 */
#include <Python.h>
#include "libsvm_file.h"
#include "string_kernel.h"
#include "sum_string_kernel.h"
#include <sstream>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>

// static PyArrayObject *
static PyObject *
sum_string_kernel(PyObject *self, PyObject *args, PyObject *keywds) {
    // Kernel parameters
    int normalize = 1;
    int verbose = 0;
    int save_output = 0;
    int return_float = 0;
    int check_min_length = 0;
    int hard_matching = 0;
    const int symbol_size = 255;  // A size of an alphabet
    const int max_length = 1000;  // A maximum sequence length
    int min_kn = 1;                   // A level of subsequence matching
    int max_kn = 2;                   // A level of subsequence matching
    double lambda = .5;          // A decay factor

    // Prepare data
    std::vector<std::string> vector_data;
    std::vector<std::string> vector_labels;

    Py_ssize_t list_size;      /* how many lines we passed for parsing */
    char * line;        /* pointer to the line as a string */

    PyObject * listObj; /* the list of strings */
    PyObject * strObj;  /* one string in the list */
    PyObject * labels = NULL; /* the list of strings */
    char * filename = (char *)"output.txt"; // default value

    static char *kwlist[] = {
        (char*)"sequences", (char*)"filename", (char*)"normalize",
        (char*)"min_kn", (char*)"max_kn", (char*)"lamda",
        (char*)"save_output", (char*)"hard_matching",
        (char*)"verbose", (char*)"return_float", (char*)"check_min_length",
        (char*)"labels", NULL
    };
    /* the O! parses for a Python object (listObj) checked to be of type PyList_Type */
    if (!PyArg_ParseTupleAndKeywords(args, keywds, "O!|siiidiiiiiO!", kwlist,
            &PyList_Type, &listObj, &filename, &normalize, &min_kn, &max_kn,
            &lambda, &save_output, &hard_matching, &verbose, &return_float,
            &check_min_length,
            &PyList_Type, &labels))
        return NULL;

    /* get the number of lines passed */
    list_size = PyList_Size(listObj);
    if (list_size < 0) return NULL; /* Not a list */

    std::string kernel_file(filename);
    std::string label;
    std::stringstream ss;
    for (Py_ssize_t i = 0; i < list_size; i++){
    	/* grab the string object from the next element of the list */
    	strObj = PyList_GetItem(listObj, i); /* Can't fail */
    	line = PyString_AsString(strObj);  /* make it a string */
        if(check_min_length && strlen(line) < min_kn) {
            min_kn = strlen(line);
        }
        vector_data.push_back(line);

        if (labels != NULL) {
            strObj = PyList_GetItem(labels, i);
        	line = PyString_AsString(strObj);
            label = std::string(line);
        } else {
            // convert i into a string
            ss << i;
            label = ss.str();
        }
        vector_labels.push_back(label);
	}

    if(verbose) {
        std::cout << "Parameters:"
        << "\n\tfilename: " << filename
        << "\n\tnormalize: " << normalize
        << "\n\tmin_kn: " << min_kn
        << "\n\tmax_kn: " << max_kn
        << "\n\tlambda: " << lambda
        << "\n\thard_matching: " << hard_matching
        << std::endl;
    }

    if(min_kn > max_kn) {
        PyErr_SetString(PyExc_ValueError, "`min_kn` is higher than `max_kn`");
        return NULL;
    }

    // Main computations
    SumStringKernel<float> string_kernel(min_kn, max_kn, normalize,
                                         symbol_size, max_length, lambda,
                                         hard_matching);
    string_kernel.set_data(vector_data);
    string_kernel.compute_kernel();

    if (save_output) {
      if (!write_kernel(kernel_file, vector_labels, string_kernel)) {
        PyErr_SetString(PyExc_IOError, "Cannot write to filename specified");
        return NULL;
      }
    }

    if(return_float && list_size == 2) {
        return Py_BuildValue("f", string_kernel.values()[1]);
    }

    // build the numpy matrix to pass back to the Python code
    // need to copy data to prevent the deleting in string kernel class
    // TODO avoid copying data?
    float * data = (float*) malloc(list_size*list_size*sizeof(float));
    if (!data) {
        PyErr_SetString(PyExc_MemoryError, "out of memory");
        return NULL;
    }
    string_kernel.copy_kernel(data);

    npy_intp* size = (npy_intp*)malloc(sizeof(npy_intp)*2);
    size[0] = size[1] = list_size;
    PyObject * py_arr = PyArray_SimpleNewFromData(2, size, NPY_FLOAT, data);
    return py_arr;
}

static PyMethodDef StringKernelMethods[] = {
    {"sum_string_kernel", (PyCFunction)sum_string_kernel, METH_VARARGS | METH_KEYWORDS,
     "docs."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC initsum_string_kernel(void) {
    (void) Py_InitModule("sum_string_kernel", StringKernelMethods);
    import_array();  // required to use PyArray_SimpleNewFromData
}

int main(int argc, char *argv[]) {
    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(argv[0]);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Add a static module */
    initsum_string_kernel();
    return 0;
}
<|endoftext|>


<commit_before>Int_t AddGoodRuns(AliAnalysisAlien* plugin,TString lhcPeriod,TString mcprod="") {
  //
  // Adds good runs from the Monalisa Run Condition Table
  //
  if(mcprod=="") plugin->SetRunPrefix("000"); // DATA

  Int_t firstrun=0,lastrun=9999999;
  Int_t nruns=0,ngoodruns=0;

  if(mcprod=="LHC10d3") {firstrun=117054;lastrun=117222;}
  if(mcprod=="LHC10d5") {firstrun=117086;lastrun=117222;}

  if(lhcPeriod=="LHC10b") {
    nruns=31;
    Int_t runlist[31]={117222, 117220, 117116, 117112, 117109, 117099, 117092, 117086, 117077, 117065, 117063, 117060, 117059, 117054, 117053, 117052, 117050, 117048, 116645, 116643, 116574, 116571, 116562, 116403, 116288, 116102, 115401, 115393, 115193, 115186, 114931};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10c") {
    nruns=36;
    Int_t runlist[36]={120829, 120825, 120824, 120823, 120822, 120821, 120820, 120758, 120750, 120741, 120671, 120617, 120616, 120505, 120504, 120503, 120244, 120079, 120076, 120073, 120072, 120069, 120067, 119862, 119859, 119856, 119853, 119849, 119846, 119845, 119844, 119842, 119841, 119163, 119161, 119159};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10dhighmu") { // only runs with high mu
    nruns=17;
    Int_t runlist[17]={124750, 124746, 124702, 124608, 124607, 124606, 124605, 124604, 124381, 124380, 124378, 124367, 124362, 124358, 124355, 124191, 124187};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10d") { // runs with high mu excluded
    nruns=55;
    Int_t runlist[55]={126437, 126432, 126425, 126424, 126422, 126409, 126408, 126407, 126406, 126405, 126404, 126403, 126359, 126352, 126351, 126350, 126285, 126284, 126283, 126168, 126167, 126160, 126158, 126097, 126090, 126088, 126082, 126081, 126078, 126073, 126008, 126007, 126004, 125855, 125851, 125850, 125849, 125848, 125847, 125844, 125843, 125842, 125633, 125632, 125630, 125296, 125134, 125101, 125100, 125097, 125085, 125023, 124751, 122375, 122374};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10e") { // updated Apr 5 (RCT good runs)
    nruns=96;
    Int_t runlist[96]={130847, 130840, 130834, 130799, 130798, 130795, 130793, 130696, 130628, 130623, 130620, 130609, 130519, 130480, 130360, 130358, 130356, 130354, 130343, 130178, 130158, 129961, 129960, 129959, 129744, 129742, 129738, 129736, 129735, 129729, 129726, 129725, 129723, 129667, 129666, 129659, 129654, 129653, 129652, 129650, 129647, 129641, 129639, 129599, 129586, 129540, 129528, 129527, 129523, 129520, 129513, 129512, 128913, 128855, 128853, 128843, 128836, 128835, 128824, 128823, 128820, 128778, 128777, 128678, 128677, 128615, 128611, 128609, 128605, 128582, 128507, 128504, 128503, 128495, 128494, 128486, 128483, 128452, 128366, 128260, 128192, 128191, 128186, 128185, 127942, 127941, 127940, 127937, 127936, 127935, 127933, 127931, 127822, 127718, 127714, 127712};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10h") {
    nruns=109;
    Int_t runlist[109]={139510, 139507, 139505, 139504, 139503, 139465, 139440, 139439, 139438, 139437, 139360, 139329, 139328, 139314, 139311, 139310, 139309, 139308, 139173, 139172, 139107, 139105, 139104, 139042, 139038, 139037, 139036, 139029, 139028, 138980, 138979, 138978, 138977, 138872, 138870, 138837, 138830, 138740, 138732, 138731, 138730, 138666, 138662, 138653, 138652, 138638, 138637, 138624, 138621, 138583, 138582, 138578, 138534, 138533, 138469, 138442, 138439, 138438, 138396, 138359, 138275, 138225, 138201, 138200, 138197, 138192, 138190, 138154, 138150, 138126, 138125, 137848, 137843, 137752, 137751, 137748, 137724, 137722, 137718, 137704, 137693, 137692, 137691, 137686, 137639, 137638, 137608, 137595, 137549, 137546, 137544, 137541, 137539, 137531, 137530, 137443, 137441, 137440, 137439, 137434, 137432, 137431, 137430, 137366, 137243, 137236, 137235, 137232, 137230};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC11a") {
    nruns=24;
    Int_t runlist[24]={146860, 146859, 146858, 146857, 146856, 146824, 146817, 146814, 146813, 146812, 146808, 146807, 146806, 146805, 146804, 146803, 146802, 146801, 146748, 146747, 146746, 146689, 146688, 146686};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  return ngoodruns;
}
<commit_msg>Update run list for LHC10h (RCT \!bad && \!vdM)<commit_after>Int_t AddGoodRuns(AliAnalysisAlien* plugin,TString lhcPeriod,TString mcprod="") {
  //
  // Adds good runs from the Monalisa Run Condition Table
  //
  if(mcprod=="") plugin->SetRunPrefix("000"); // DATA

  Int_t firstrun=0,lastrun=9999999;
  Int_t nruns=0,ngoodruns=0;

  if(mcprod=="LHC10d3") {firstrun=117054;lastrun=117222;}
  if(mcprod=="LHC10d5") {firstrun=117086;lastrun=117222;}

  if(lhcPeriod=="LHC10b") {
    nruns=31;
    Int_t runlist[31]={117222, 117220, 117116, 117112, 117109, 117099, 117092, 117086, 117077, 117065, 117063, 117060, 117059, 117054, 117053, 117052, 117050, 117048, 116645, 116643, 116574, 116571, 116562, 116403, 116288, 116102, 115401, 115393, 115193, 115186, 114931};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10c") {
    nruns=36;
    Int_t runlist[36]={120829, 120825, 120824, 120823, 120822, 120821, 120820, 120758, 120750, 120741, 120671, 120617, 120616, 120505, 120504, 120503, 120244, 120079, 120076, 120073, 120072, 120069, 120067, 119862, 119859, 119856, 119853, 119849, 119846, 119845, 119844, 119842, 119841, 119163, 119161, 119159};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10dhighmu") { // only runs with high mu
    nruns=17;
    Int_t runlist[17]={124750, 124746, 124702, 124608, 124607, 124606, 124605, 124604, 124381, 124380, 124378, 124367, 124362, 124358, 124355, 124191, 124187};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10d") { // runs with high mu excluded
    nruns=55;
    Int_t runlist[55]={126437, 126432, 126425, 126424, 126422, 126409, 126408, 126407, 126406, 126405, 126404, 126403, 126359, 126352, 126351, 126350, 126285, 126284, 126283, 126168, 126167, 126160, 126158, 126097, 126090, 126088, 126082, 126081, 126078, 126073, 126008, 126007, 126004, 125855, 125851, 125850, 125849, 125848, 125847, 125844, 125843, 125842, 125633, 125632, 125630, 125296, 125134, 125101, 125100, 125097, 125085, 125023, 124751, 122375, 122374};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10e") { // updated Apr 5 (RCT good runs)
    nruns=96;
    Int_t runlist[96]={130847, 130840, 130834, 130799, 130798, 130795, 130793, 130696, 130628, 130623, 130620, 130609, 130519, 130480, 130360, 130358, 130356, 130354, 130343, 130178, 130158, 129961, 129960, 129959, 129744, 129742, 129738, 129736, 129735, 129729, 129726, 129725, 129723, 129667, 129666, 129659, 129654, 129653, 129652, 129650, 129647, 129641, 129639, 129599, 129586, 129540, 129528, 129527, 129523, 129520, 129513, 129512, 128913, 128855, 128853, 128843, 128836, 128835, 128824, 128823, 128820, 128778, 128777, 128678, 128677, 128615, 128611, 128609, 128605, 128582, 128507, 128504, 128503, 128495, 128494, 128486, 128483, 128452, 128366, 128260, 128192, 128191, 128186, 128185, 127942, 127941, 127940, 127937, 127936, 127935, 127933, 127931, 127822, 127718, 127714, 127712};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC10h") {
    nruns=122;
    Int_t runlist[122]={139517, 139514, 139513, 139511, 139510, 139507, 139505, 139504, 139503, 139471, 139470, 139467, 139466, 139465, 139441, 139440, 139439, 139438, 139437, 139360, 139329, 139328, 139316, 139314, 139311, 139310, 139309, 139308, 139173, 139110, 139107, 139105, 139104, 139042, 139038, 139037, 139036, 139029, 139028, 138980, 138979, 138978, 138977, 138872, 138871, 138870, 138837, 138796, 138795, 138740, 138732, 138731, 138730, 138666, 138662, 138653, 138652, 138638, 138637, 138624, 138621, 138583, 138582, 138579, 138578, 138534, 138469, 138442, 138439, 138438, 138396, 138364, 138359, 138275, 138225, 138201, 138200, 138197, 138192, 138190, 137848, 137843, 137752, 137751, 137748, 137724, 137722, 137718, 137704, 137693, 137692, 137691, 137686, 137685, 137639, 137638, 137608, 137595, 137549, 137546, 137544, 137541, 137539, 137531, 137530, 137443, 137441, 137440, 137439, 137434, 137432, 137431, 137430, 137366, 137243, 137236, 137235, 137232, 137231, 137165, 137162, 137161};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  if(lhcPeriod=="LHC11a") {
    nruns=24;
    Int_t runlist[24]={146860, 146859, 146858, 146857, 146856, 146824, 146817, 146814, 146813, 146812, 146808, 146807, 146806, 146805, 146804, 146803, 146802, 146801, 146748, 146747, 146746, 146689, 146688, 146686};

    for(Int_t k=0;k<nruns;k++){
      if(runlist[k]<firstrun || runlist[k]>lastrun) continue;
      plugin->AddRunNumber(runlist[k]);
      ngoodruns++;
    }
    plugin->SetNrunsPerMaster(ngoodruns);
  }

  return ngoodruns;
}
<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * 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.
 *
 * 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 HOLDER 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.
 *
 * \file SimpleStack.hxx
 *
 * A complete OpenLCB stack for use in straightforward OpenLCB nodes.
 *
 * @author Balazs Racz
 * @date 10 Mar 2015
 */

#ifndef _NMRANET_SIMPLESTACK_HXX_
#define _NMRANET_SIMPLESTACK_HXX_

#include <fcntl.h>

#include "executor/Executor.hxx"
#include "nmranet/AliasAllocator.hxx"
#include "nmranet/DatagramCan.hxx"
#include "nmranet/DefaultNode.hxx"
#include "nmranet/EventService.hxx"
#include "nmranet/IfCan.hxx"
#include "nmranet/MemoryConfig.hxx"
#include "nmranet/ProtocolIdentification.hxx"
#include "utils/GcTcpHub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/HubDevice.hxx"
#include "utils/HubDeviceNonBlock.hxx"
#include "nmranet_config.h"

namespace nmranet
{

class SimpleCanStack
{
public:
    static const unsigned EXECUTOR_PRIORITIES = 5;

    SimpleCanStack(const nmranet::NodeID node_id);

    Executor<EXECUTOR_PRIORITIES> *executor()
    {
        return &executor_;
    }

    Service *service()
    {
        return &service_;
    }

    IfCan *interface()
    {
        return &ifCan_;
    }

    Node *node()
    {
        return &node_;
    }

    CanHubFlow *can_hub()
    {
        return &canHub0_;
    }

    /** Adds a CAN bus port with synchronous driver API. */
    void add_can_port_blocking(const char *device)
    {
        int can_fd = ::open(device, O_RDWR);
        HASSERT(can_fd >= 0);
        auto *port = new FdHubPort<CanHubFlow>(
            &canHub0_, can_fd, EmptyNotifiable::DefaultInstance());
        additionalComponents_.emplace_back(port);
    }

#ifdef __FreeRTOS__
    /** Adds a CAN bus port with asynchronous driver API. */
    void add_can_port_async(const char *device)
    {
        auto* port = new HubDeviceNonBlock<CanHubFlow>(&canHub0_, device);
        additionalComponents_.emplace_back(port);
    }
#endif

    /** Adds a gridconnect port to the CAN bus. */
    void add_gridconnect_port(const char* device) {
        int fd = ::open(device, O_RDWR);
        HASSERT(fd >= 0);
        create_gc_port_for_can_hub(&canHub0_, fd);
    }

    /** Starts a TCP server on the specified port in listening mode. Each
     * incoming connection will be assumed to be in gridconnect protocol and
     * will be added to the gridconnect hub. */
    void start_tcp_hub_server(int port)
    {
        /// @TODO (balazs.racz) make this more efficient by rendering to string
        /// only once for all connections.
        /// @TODO (balazs.racz) do not leak this.
        new GcTcpHub(&canHub0_, port);
    }

    /** Causes all CAN packets to be printed to stdout. */
    void print_all_packets()
    {
        auto *port = new DisplayPort(&service_);
        gridconnect_hub()->register_port(port);
        additionalComponents_.emplace_back(port);
    }

    /** Returns the hub to be used for gridconnect-format CANbus. You can
     * inject text CAN packets to this hub, add printers and in general connect
     * devices and sockets using the gridconnect protocol to talk CANbus.
     *
     * The actual gridconnect parser / renderer objects will be created upon
     * the first call to this function. */
    HubFlow *gridconnect_hub()
    {
        if (!gcHub_)
        {
            gcHub_.reset(new HubFlow(&service_));
            gcAdapter_.reset(GCAdapterBase::CreateGridConnectAdapter(
                gcHub_.get(), &canHub0_, false));
        }
        return gcHub_.get();
    }

    /** Donates the current thread to the executor. Never returns. */
    void loop_executor()
    {
        start_stack();
        executor_.thread_body();
    }

    /** Instructs the executor to create a new thread and run in there. */
    void start_executor_thread(const char *name, int priority,
                               size_t stack_size)
    {
        start_stack();
        executor_.start_thread(name, priority, stack_size);
    }

private:
    static const auto PIP_RESPONSE = Defs::EVENT_EXCHANGE;

    /** Call this function once after the actual IO ports are set up. Calling
     * before the executor starts looping is okay. */
    void start_stack();

    /// This executor's threads will be handled
    Executor<EXECUTOR_PRIORITIES> executor_{NO_THREAD()};
    /// Default service on the particular executor.
    Service service_{&executor_};
    /// Abstract CAN bus in-memory.
    CanHubFlow canHub0_{&service_};
    /** NMRAnet interface for sending and receiving messages, formatting them
     * to the CAN bus port and maintaining the conversion flows, caches etc. */
    IfCan ifCan_{
        &executor_,                      &canHub0_,
        config_local_alias_cache_size(), config_remote_alias_cache_size(),
        config_local_nodes_count()};
    /// The actual node.
    DefaultNode node_;
    /// Dispatches event protocol requests to the event handlers.
    EventService eventService_{&ifCan_};
    /// Handles PIP requests.
    ProtocolIdentificationHandler pipHandler_{&node_, PIP_RESPONSE};

    CanDatagramService datagramService_{&ifCan_,
        config_num_datagram_registry_entries(), config_num_datagram_clients()};
    MemoryConfigHandler memoryConfigHandler_{&datagramService_,
            &node_, config_num_memory_spaces()};

    /** All packets are forwarded to this hub in gridconnect format, if
     * needed. Will be initialized upon first use. */
    std::unique_ptr<HubFlow> gcHub_;
    /** Bridge between canHub_ and gcHub_. Lazily initialized. */
    std::unique_ptr<GCAdapterBase> gcAdapter_;

    /// Stores and keeps ownership of optional components.
    std::vector<std::unique_ptr<Destructable>> additionalComponents_;
};

} // namespace nmranet

#endif //  _NMRANET_SIMPLESTACK_HXX_
<commit_msg>Simple Stack fixes: - adds SNIP handler. - fixes startup crash due to lacking initialize flow.<commit_after>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * 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.
 *
 * 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 HOLDER 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.
 *
 * \file SimpleStack.hxx
 *
 * A complete OpenLCB stack for use in straightforward OpenLCB nodes.
 *
 * @author Balazs Racz
 * @date 10 Mar 2015
 */

#ifndef _NMRANET_SIMPLESTACK_HXX_
#define _NMRANET_SIMPLESTACK_HXX_

#include <fcntl.h>

#include "executor/Executor.hxx"
#include "nmranet/AliasAllocator.hxx"
#include "nmranet/DatagramCan.hxx"
#include "nmranet/DefaultNode.hxx"
#include "nmranet/EventService.hxx"
#include "nmranet/IfCan.hxx"
#include "nmranet/MemoryConfig.hxx"
#include "nmranet/NodeInitializeFlow.hxx"
#include "nmranet/ProtocolIdentification.hxx"
#include "nmranet/SimpleNodeInfo.hxx"
#include "nmranet_config.h"
#include "utils/GcTcpHub.hxx"
#include "utils/GridConnectHub.hxx"
#include "utils/HubDevice.hxx"
#include "utils/HubDeviceNonBlock.hxx"

namespace nmranet
{

class SimpleCanStack
{
public:
    static const unsigned EXECUTOR_PRIORITIES = 5;

    SimpleCanStack(const nmranet::NodeID node_id);

    Executor<EXECUTOR_PRIORITIES> *executor()
    {
        return &executor_;
    }

    Service *service()
    {
        return &service_;
    }

    IfCan *interface()
    {
        return &ifCan_;
    }

    Node *node()
    {
        return &node_;
    }

    CanHubFlow *can_hub()
    {
        return &canHub0_;
    }

    /** Adds a CAN bus port with synchronous driver API. */
    void add_can_port_blocking(const char *device)
    {
        int can_fd = ::open(device, O_RDWR);
        HASSERT(can_fd >= 0);
        auto *port = new FdHubPort<CanHubFlow>(
            &canHub0_, can_fd, EmptyNotifiable::DefaultInstance());
        additionalComponents_.emplace_back(port);
    }

#ifdef __FreeRTOS__
    /** Adds a CAN bus port with asynchronous driver API. */
    void add_can_port_async(const char *device)
    {
        auto* port = new HubDeviceNonBlock<CanHubFlow>(&canHub0_, device);
        additionalComponents_.emplace_back(port);
    }
#endif

    /** Adds a gridconnect port to the CAN bus. */
    void add_gridconnect_port(const char* device) {
        int fd = ::open(device, O_RDWR);
        HASSERT(fd >= 0);
        create_gc_port_for_can_hub(&canHub0_, fd);
    }

    /** Starts a TCP server on the specified port in listening mode. Each
     * incoming connection will be assumed to be in gridconnect protocol and
     * will be added to the gridconnect hub. */
    void start_tcp_hub_server(int port)
    {
        /// @TODO (balazs.racz) make this more efficient by rendering to string
        /// only once for all connections.
        /// @TODO (balazs.racz) do not leak this.
        new GcTcpHub(&canHub0_, port);
    }

    /** Causes all CAN packets to be printed to stdout. */
    void print_all_packets()
    {
        auto *port = new DisplayPort(&service_);
        gridconnect_hub()->register_port(port);
        additionalComponents_.emplace_back(port);
    }

    /** Returns the hub to be used for gridconnect-format CANbus. You can
     * inject text CAN packets to this hub, add printers and in general connect
     * devices and sockets using the gridconnect protocol to talk CANbus.
     *
     * The actual gridconnect parser / renderer objects will be created upon
     * the first call to this function. */
    HubFlow *gridconnect_hub()
    {
        if (!gcHub_)
        {
            gcHub_.reset(new HubFlow(&service_));
            gcAdapter_.reset(GCAdapterBase::CreateGridConnectAdapter(
                gcHub_.get(), &canHub0_, false));
        }
        return gcHub_.get();
    }

    /** Donates the current thread to the executor. Never returns. */
    void loop_executor()
    {
        start_stack();
        executor_.thread_body();
    }

    /** Instructs the executor to create a new thread and run in there. */
    void start_executor_thread(const char *name, int priority,
                               size_t stack_size)
    {
        start_stack();
        executor_.start_thread(name, priority, stack_size);
    }

private:
    static const auto PIP_RESPONSE = Defs::EVENT_EXCHANGE;

    /** Call this function once after the actual IO ports are set up. Calling
     * before the executor starts looping is okay. */
    void start_stack();

    /// This executor's threads will be handled
    Executor<EXECUTOR_PRIORITIES> executor_{NO_THREAD()};
    /// Default service on the particular executor.
    Service service_{&executor_};
    /// Abstract CAN bus in-memory.
    CanHubFlow canHub0_{&service_};
    /** NMRAnet interface for sending and receiving messages, formatting them
     * to the CAN bus port and maintaining the conversion flows, caches etc. */
    IfCan ifCan_{
        &executor_,                      &canHub0_,
        config_local_alias_cache_size(), config_remote_alias_cache_size(),
        config_local_nodes_count()};
    /// The initialization flow takes care for node startup duties.
    InitializeFlow initFlow_{&service_};
    /// The actual node.
    DefaultNode node_;
    /// Dispatches event protocol requests to the event handlers.
    EventService eventService_{&ifCan_};
    /// Handles PIP requests.
    ProtocolIdentificationHandler pipHandler_{&node_, PIP_RESPONSE};
    /// General flow for simple info requests.
    SimpleInfoFlow infoFlow_{&ifCan_};
    /// Handles SNIP requests.
    SNIPHandler snipHandler_{&ifCan_, &infoFlow_};

    CanDatagramService datagramService_{&ifCan_,
        config_num_datagram_registry_entries(), config_num_datagram_clients()};
    MemoryConfigHandler memoryConfigHandler_{&datagramService_,
            &node_, config_num_memory_spaces()};

    /** All packets are forwarded to this hub in gridconnect format, if
     * needed. Will be initialized upon first use. */
    std::unique_ptr<HubFlow> gcHub_;
    /** Bridge between canHub_ and gcHub_. Lazily initialized. */
    std::unique_ptr<GCAdapterBase> gcAdapter_;

    /// Stores and keeps ownership of optional components.
    std::vector<std::unique_ptr<Destructable>> additionalComponents_;
};

} // namespace nmranet

#endif //  _NMRANET_SIMPLESTACK_HXX_
<|endoftext|>