<commit_before>
/**
 * 所有 #include <外部文件> 的头文件 都必须保证 本文件被首先#include
 * 以下项目可以由本文件保证包含：
 * 	<cstdint>
 * 	<cstddef>
 * 	并保证 全局名称空间包含所有stdint。
 * 	CS_DEBUG = 1 时保证 #include <iostream>
 */

#pragma once

/**
 * 平台兼容原则：以不大的代价换取一定的兼容性；以首要目标平台0-overhead为前提。
 */

#ifndef NDEBUG
#	ifndef CS_DEBUG
#   	define CS_DEBUG		2
#	endif
#	ifndef CS_LOG_ON
#		define CS_LOG_ON	1
#	endif
#else
#	undef CS_DEBUG
#	define CS_DEBUG			0
#	undef CS_LOG_ON
#	define CS_LOG_ON		0
#endif

#if ! CS_DEBUG
#ifndef NDEBUG
#	define NDEBUG
#endif
#	define BOOST_DISABLE_ASSERTS
#endif

#if defined(__cplusplus) && __cplusplus >= 201103L
#   define CS_CPP11 1
#else
#   define CS_CPP11 0
#endif

// Use wchar_t/wstring wcout/wcerr/wcin wfstream or not.
// It's just a standard, not make used in this file.
#ifndef CS_USE_WCS
#	define CS_USE_WCS	0
#endif
// Use wcout/wcerr/wcin or not. This will make use in this file.
#ifndef CS_USE_WIO
#	define CS_USE_WIO	0
#endif

#if defined(CS_USE_WCS) && CS_USE_WCS
#	define CS_STR_LITER(str_liter)		L##str_liter
#else
#	define CS_STR_LITER(str_liter)		#str_liter
#endif

#ifndef __GNUC__
#   define __attribute__(...)
#endif

#ifdef __cplusplus
// avoid from boost if possible.
#	if defined(__GNUC__)	\
		&& (!defined(__GXX_EXPERIMENTAL_CXX0X__) || !__GXX_EXPERIMENTAL_CXX0X__)
#		include <boost/cstdint.hpp>
#	else
#		include <cstdint>
#	endif
#	include <cstddef>
#else
#	include <stdint.h>
#	include <stddef.h>
#endif

#define CS_EXIT_STATUS_FAILED EXIT_FAILURE

#ifdef __cplusplus
#	define CS_PREF_STD(symbol)		::std::symbol
#else
#	define CS_PREF_STD(symbol)		symbol
#endif

#if CS_USE_WIO
#	define CS_STDIN		::std::wcin
#	define CS_STDOUT	::std::wcout
#	define CS_STDERR	::std::wcerr
#else
#	define CS_STDIN		::std::cin
#	define CS_STDOUT	::std::cout
#	define CS_STDERR	::std::cerr
#endif

#ifdef __linux__
#   define CS_OC_BLACK_BEGIN    "\033[32;30;5m"
#   define CS_OC_BLUE_BEGIN     "\033[32;34;5m"
#   define CS_OC_RED_BEGIN      "\033[32;31;5m"
#   define CS_OC_GREEN_BEGIN    "\033[32;49;5m"
#   define CS_OC_END            "\033[0m"
#   define CS_OC_BLACK(...)     CS_OC_BLACK_BEGIN   << __VA_ARGS__ << CS_OC_END
#   define CS_OC_BLUE(...)      CS_OC_BLUE_BEGIN    << __VA_ARGS__ << CS_OC_END
#   define CS_OC_RED(...)       CS_OC_RED_BEGIN     << __VA_ARGS__ << CS_OC_END
#   define CS_OC_GREEN(...)     CS_OC_GREEN_BEGIN   << __VA_ARGS__ << CS_OC_END
#else
#   define CS_OC_BLACK_BEGIN    ""
#   define CS_OC_BLUE_BEGIN     ""
#   define CS_OC_RED_BEGIN      ""
#   define CS_OC_GREEN_BEGIN    ""
#   define CS_OC_END            ""
#   define CS_OC_BLACK(...) __VA_ARGS__
#   define CS_OC_BLUE(...)  __VA_ARGS__
#   define CS_OC_RED(...)   __VA_ARGS__
#   define CS_OC_GREEN(...) __VA_ARGS__
#endif

// line-seperator, should only use for IO..
#ifdef __linux__
#	define CS_LINESEP		'\n'
#	define CS_LINESEP_STR	"\n"
#else
#	ifdef(__WIN32__)
#		define CS_LINESEP		"\r\n"
#		define CS_LINESEP_STR	CS_LINESEP
#	else
#		define CS_LINESEP		::std::endl
#		define CS_LINESEP_STR	::std::endl()
#	endif
#endif

#if CS_DEBUG
#   define CS_DEBUG_OMIT(...)
#   include <iostream>
#   if CS_DEBUG > 1
#		if CS_USE_WCS
#			define CS_OUT(ostream, ...)											\
				do {															\
				ostream << __FILE__ << ":" << __LINE__							\
					<< ":" << __FUNCTION__ << "()" << ":\t"						\
					<< __VA_ARGS__												\
					<< ::std::endl;												\
				} while(false);
#		else
#       	define CS_OUT(ostream, ...)											\
				do {															\
				ostream << CS_OC_BLACK(__FILE__ << ":" << __LINE__)				\
					<< ":" << CS_OC_BLUE(__FUNCTION__ << "()") << ":\t"			\
					<< CS_OC_GREEN(__VA_ARGS__)									\
					<< ::std::endl;												\
				} while(false);
#		endif
#   else
#		define CS_OUT(ostream, ...)	do {ostream << __VA_ARGS__ << ::std::endl;} while(false);
#   endif
#else
#   define CS_DEBUG_OMIT(...)    __VA_ARGS__
#	define CS_OUT(ostream, ...)
#endif

#define CS_SAY(...)		CS_OUT(CS_STDOUT, __VA_ARGS__)

// NOTE: 要自行 #include <iostream>
#define CS_ECHO(...)	CS_STDOUT << __VA_ARGS__ << ::std::endl;
#define CS_ERR(...)		CS_STDERR << CS_OC_RED(__VA_ARGS__) << ::std::endl;

// #define CS_DUMP(...)	CS_OUT(CS_STDOUT, GOL_OC_BLUE(#__VA_ARGS__) << ": " << GOL_OC_GREEN(__VA_ARGS__))

#define CS_DUMP(...)																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":[" << CS_OC_GREEN(__VA_ARGS__) << "]")
#define CS_DUMP_N(...) 																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":" << ::std::endl << CS_OC_GREEN(__VA_ARGS__))

// #define CS_ERR(msg)
//	CS_STDERR << msg << ::std::endl
// --- 要自行 #include <cstdlib>
#if CS_DEBUG
#   define CS_DIE(msg)                                                          \
    CS_ERR(msg);                                                                \
    ::std::abort();
#else
#   define CS_DIE(msg)															\
	CS_ERR(msg); 																\
    ::std::exit(CS_EXIT_STATUS_FAILED)
#endif

#ifndef CS_USED
#	ifdef __GNUC__
#		define CS_USED __attribute__((__used__))
#	else
#		define CS_USED
#	endif
#endif

#ifndef CS_ATTR_CONST
#	ifdef __GNUC__
#		define CS_ATTR_CONST __attribute__((const))
#	else
#		define CS_ATTR_CONST
#	endif
#endif

#ifndef CS_MUST_CHECK
#	ifdef __GNUC__
#		define CS_MUST_CHECK __attribute__((warn_unused_result))
#	else
#		define CS_MUST_CHECK
#	endif
#endif

#ifndef CS_DEPRECATED
#	ifdef __GNUC__
#		define CS_DEPRECATED __attribute__((deprecated))
#	else
#		define CS_DEPRECATED
#	endif
#endif

#ifndef CS_FORCE_INLINE
#   ifdef __GNUC__
#       define CS_FORCE_INLINE __attribute__((always_inline))
#   else
#       define CS_FORCE_INLINE inline
#   endif
#endif

#if !defined(CS_LIKELY) && !defined(CS_UNLIKELY)
#	ifdef __GNUC__
#		define CS_LIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 1)
#		define CS_UNLIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 0)
#		define CS_BLIKELY(...)		__builtin_expect((__VA_ARGS__), true)
#		define CS_BUNLIKELY(...)	__builtin_expect((__VA_ARGS__), false)
#	else
#		define CS_LIKELY(expr)		(expr)
#		define CS_UNLIKELY(expr)	(expr)
#		define CS_BLIKELY(expr)		(expr)
#		define CS_BUNLIKELY(expr)	(expr)
#	endif
#endif

#ifndef CS_PREFETCH
#	ifdef __GNUC__
#		define CS_PREFETCH(addr,rw,clean) __builtin_prefetch(addr,rw,clean)
#	else
#		define CS_PREFETCH(addr,rw,clean)
#	endif
#endif

#define CS_RETURN_IF_NORMAL(cond, ...)		\
if (cond)									\
{											\
	return __VA_ARGS__;						\
}
#define CS_RETURN_IF(cond, ...) CS_RETURN_IF_NORMAL(CS_BUNLIKELY(cond), __VA_ARGS__)

#define CS_ABORT_IF_NORMAL(cond)			\
if (cond)									\
{											\
	::std::exit(CS_EXIT_STATUS_FAILED);		\
}
#define CS_ABORT_IF(cond) CS_ABORT_IF_NORMAL(CS_BUNLIKELY(cond))

#define _CS_DIE_IF_NORMAL(cond, info, why)	\
if (cond)									\
{											\
	CS_DIE(__FILE__ << ":" << __LINE__ << "::" << __FUNCTION__ << "() die on " << info << ", results from {" << #why << "}.");  \
}
#define CS_DIE_IF_NORMAL(cond, info) CS_DIE_IF_NORMAL(cond, info, cond)
#define CS_DIE_IF(cond, info) _CS_DIE_IF_NORMAL(CS_BUNLIKELY(cond), info, cond)
<commit_msg>no ansi color when CS_DEBUG<=1<commit_after>
/**
 * 所有 #include <外部文件> 的头文件 都必须保证 本文件被首先#include
 * 以下项目可以由本文件保证包含：
 * 	<cstdint>
 * 	<cstddef>
 * 	并保证 全局名称空间包含所有stdint。
 * 	CS_DEBUG = 1 时保证 #include <iostream>
 */

#pragma once

/**
 * 平台兼容原则：以不大的代价换取一定的兼容性；以首要目标平台0-overhead为前提。
 */

#ifndef NDEBUG
#	ifndef CS_DEBUG
#   	define CS_DEBUG		2
#	endif
#	ifndef CS_LOG_ON
#		define CS_LOG_ON	1
#	endif
#else
#	undef CS_DEBUG
#	define CS_DEBUG			0
#	undef CS_LOG_ON
#	define CS_LOG_ON		0
#endif

#if ! CS_DEBUG
#ifndef NDEBUG
#	define NDEBUG
#endif
#	define BOOST_DISABLE_ASSERTS
#endif

#if defined(__cplusplus) && __cplusplus >= 201103L
#   define CS_CPP11 1
#else
#   define CS_CPP11 0
#endif

// Use wchar_t/wstring wcout/wcerr/wcin wfstream or not.
// It's just a standard, not make used in this file.
#ifndef CS_USE_WCS
#	define CS_USE_WCS	0
#endif
// Use wcout/wcerr/wcin or not. This will make use in this file.
#ifndef CS_USE_WIO
#	define CS_USE_WIO	0
#endif

#if defined(CS_USE_WCS) && CS_USE_WCS
#	define CS_STR_LITER(str_liter)		L##str_liter
#else
#	define CS_STR_LITER(str_liter)		#str_liter
#endif

#ifndef __GNUC__
#   define __attribute__(...)
#endif

#ifdef __cplusplus
// avoid from boost if possible.
#	if defined(__GNUC__)	\
		&& (!defined(__GXX_EXPERIMENTAL_CXX0X__) || !__GXX_EXPERIMENTAL_CXX0X__)
#		include <boost/cstdint.hpp>
#	else
#		include <cstdint>
#	endif
#	include <cstddef>
#else
#	include <stdint.h>
#	include <stddef.h>
#endif

#define CS_EXIT_STATUS_FAILED EXIT_FAILURE

#ifdef __cplusplus
#	define CS_PREF_STD(symbol)		::std::symbol
#else
#	define CS_PREF_STD(symbol)		symbol
#endif

#if CS_USE_WIO
#	define CS_STDIN		::std::wcin
#	define CS_STDOUT	::std::wcout
#	define CS_STDERR	::std::wcerr
#else
#	define CS_STDIN		::std::cin
#	define CS_STDOUT	::std::cout
#	define CS_STDERR	::std::cerr
#endif

#if CS_DEBUG > 1 && defined(__linux__)
#   define CS_OC_BLACK_BEGIN    "\033[32;30;5m"
#   define CS_OC_BLUE_BEGIN     "\033[32;34;5m"
#   define CS_OC_RED_BEGIN      "\033[32;31;5m"
#   define CS_OC_GREEN_BEGIN    "\033[32;49;5m"
#   define CS_OC_END            "\033[0m"
#   define CS_OC_BLACK(...)     CS_OC_BLACK_BEGIN   << __VA_ARGS__ << CS_OC_END
#   define CS_OC_BLUE(...)      CS_OC_BLUE_BEGIN    << __VA_ARGS__ << CS_OC_END
#   define CS_OC_RED(...)       CS_OC_RED_BEGIN     << __VA_ARGS__ << CS_OC_END
#   define CS_OC_GREEN(...)     CS_OC_GREEN_BEGIN   << __VA_ARGS__ << CS_OC_END
#else
#   define CS_OC_BLACK_BEGIN    ""
#   define CS_OC_BLUE_BEGIN     ""
#   define CS_OC_RED_BEGIN      ""
#   define CS_OC_GREEN_BEGIN    ""
#   define CS_OC_END            ""
#   define CS_OC_BLACK(...) __VA_ARGS__
#   define CS_OC_BLUE(...)  __VA_ARGS__
#   define CS_OC_RED(...)   __VA_ARGS__
#   define CS_OC_GREEN(...) __VA_ARGS__
#endif

// line-seperator, should only use for IO..
#ifdef __linux__
#	define CS_LINESEP		'\n'
#	define CS_LINESEP_STR	"\n"
#else
#	ifdef(__WIN32__)
#		define CS_LINESEP		"\r\n"
#		define CS_LINESEP_STR	CS_LINESEP
#	else
#		define CS_LINESEP		::std::endl
#		define CS_LINESEP_STR	::std::endl()
#	endif
#endif

#if CS_DEBUG
#   define CS_DEBUG_OMIT(...)
#   include <iostream>
#   if CS_DEBUG > 1
#		if CS_USE_WCS
#			define CS_OUT(ostream, ...)											\
				do {															\
				ostream << __FILE__ << ":" << __LINE__							\
					<< ":" << __FUNCTION__ << "()" << ":\t"						\
					<< __VA_ARGS__												\
					<< ::std::endl;												\
				} while(false);
#		else
#       	define CS_OUT(ostream, ...)											\
				do {															\
				ostream << CS_OC_BLACK(__FILE__ << ":" << __LINE__)				\
					<< ":" << CS_OC_BLUE(__FUNCTION__ << "()") << ":\t"			\
					<< CS_OC_GREEN(__VA_ARGS__)									\
					<< ::std::endl;												\
				} while(false);
#		endif
#   else
#		define CS_OUT(ostream, ...)	do {ostream << __VA_ARGS__ << ::std::endl;} while(false);
#   endif
#else
#   define CS_DEBUG_OMIT(...)    __VA_ARGS__
#	define CS_OUT(ostream, ...)
#endif

#define CS_SAY(...)		CS_OUT(CS_STDOUT, __VA_ARGS__)

// NOTE: 要自行 #include <iostream>
#define CS_ECHO(...)	CS_STDOUT << __VA_ARGS__ << ::std::endl;
#define CS_ERR(...)		CS_STDERR << CS_OC_RED(__VA_ARGS__) << ::std::endl;

// #define CS_DUMP(...)	CS_OUT(CS_STDOUT, GOL_OC_BLUE(#__VA_ARGS__) << ": " << GOL_OC_GREEN(__VA_ARGS__))

#define CS_DUMP(...)																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":[" << CS_OC_GREEN(__VA_ARGS__) << "]")
#define CS_DUMP_N(...) 																	\
	CS_OUT(CS_STDOUT, CS_OC_RED(#__VA_ARGS__) << ":" << ::std::endl << CS_OC_GREEN(__VA_ARGS__))

// #define CS_ERR(msg)
//	CS_STDERR << msg << ::std::endl
// --- 要自行 #include <cstdlib>
#if CS_DEBUG
#   define CS_DIE(msg)                                                          \
    CS_ERR(msg);                                                                \
    ::std::abort();
#else
#   define CS_DIE(msg)															\
	CS_ERR(msg); 																\
    ::std::exit(CS_EXIT_STATUS_FAILED)
#endif

#ifndef CS_USED
#	ifdef __GNUC__
#		define CS_USED __attribute__((__used__))
#	else
#		define CS_USED
#	endif
#endif

#ifndef CS_ATTR_CONST
#	ifdef __GNUC__
#		define CS_ATTR_CONST __attribute__((const))
#	else
#		define CS_ATTR_CONST
#	endif
#endif

#ifndef CS_MUST_CHECK
#	ifdef __GNUC__
#		define CS_MUST_CHECK __attribute__((warn_unused_result))
#	else
#		define CS_MUST_CHECK
#	endif
#endif

#ifndef CS_DEPRECATED
#	ifdef __GNUC__
#		define CS_DEPRECATED __attribute__((deprecated))
#	else
#		define CS_DEPRECATED
#	endif
#endif

#ifndef CS_FORCE_INLINE
#   ifdef __GNUC__
#       define CS_FORCE_INLINE __attribute__((always_inline))
#   else
#       define CS_FORCE_INLINE inline
#   endif
#endif

#if !defined(CS_LIKELY) && !defined(CS_UNLIKELY)
#	ifdef __GNUC__
#		define CS_LIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 1)
#		define CS_UNLIKELY(...)		__builtin_expect(!!(__VA_ARGS__), 0)
#		define CS_BLIKELY(...)		__builtin_expect((__VA_ARGS__), true)
#		define CS_BUNLIKELY(...)	__builtin_expect((__VA_ARGS__), false)
#	else
#		define CS_LIKELY(expr)		(expr)
#		define CS_UNLIKELY(expr)	(expr)
#		define CS_BLIKELY(expr)		(expr)
#		define CS_BUNLIKELY(expr)	(expr)
#	endif
#endif

#ifndef CS_PREFETCH
#	ifdef __GNUC__
#		define CS_PREFETCH(addr,rw,clean) __builtin_prefetch(addr,rw,clean)
#	else
#		define CS_PREFETCH(addr,rw,clean)
#	endif
#endif

#define CS_RETURN_IF_NORMAL(cond, ...)		\
if (cond)									\
{											\
	return __VA_ARGS__;						\
}
#define CS_RETURN_IF(cond, ...) CS_RETURN_IF_NORMAL(CS_BUNLIKELY(cond), __VA_ARGS__)

#define CS_ABORT_IF_NORMAL(cond)			\
if (cond)									\
{											\
	::std::exit(CS_EXIT_STATUS_FAILED);		\
}
#define CS_ABORT_IF(cond) CS_ABORT_IF_NORMAL(CS_BUNLIKELY(cond))

#define _CS_DIE_IF_NORMAL(cond, info, why)	\
if (cond)									\
{											\
	CS_DIE(__FILE__ << ":" << __LINE__ << "::" << __FUNCTION__ << "() die on " << info << ", results from {" << #why << "}.");  \
}
#define CS_DIE_IF_NORMAL(cond, info) CS_DIE_IF_NORMAL(cond, info, cond)
#define CS_DIE_IF(cond, info) _CS_DIE_IF_NORMAL(CS_BUNLIKELY(cond), info, cond)
<|endoftext|>


<commit_before>/**
* @file      UtilsTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license   BSD, see the @c LICENSE file for more details
* @brief     Tests for the utilities.
*/

#include <gtest/gtest.h>

#include "TestUtils.h"
#include "Utils.h"

namespace bencoding {
namespace tests {

using namespace testing;

class UtilsTests: public Test {};

//
// strToNum()
//

TEST_F(UtilsTests,
StrToNumWithValidDecimalIntegerSucceeds) {
	int num = 0;
	EXPECT_TRUE(strToNum("-1000", num, std::dec));
	EXPECT_EQ(-1000, num);

	num = 0;
	EXPECT_TRUE(strToNum("-1", num, std::dec));
	EXPECT_EQ(-1, num);

	num = 0;
	EXPECT_TRUE(strToNum("0", num, std::dec));
	EXPECT_EQ(0, num);

	num = 0;
	EXPECT_TRUE(strToNum("1", num, std::dec));
	EXPECT_EQ(1, num);

	num = 0;
	EXPECT_TRUE(strToNum("1000", num, std::dec));
	EXPECT_EQ(1000, num);

	num = 0;
	EXPECT_TRUE(strToNum("0000", num, std::dec));
	EXPECT_EQ(0, num);

	num = 0;
	EXPECT_TRUE(strToNum("0003", num, std::dec));
	EXPECT_EQ(3, num);
}

TEST_F(UtilsTests,
StrToNumWithInvalidDecimalIntegerFails) {
	int num = -1;
	EXPECT_FALSE(strToNum("", num, std::dec));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("zzz", num, std::dec));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("13 something", num, std::dec));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("13something", num, std::dec));
	EXPECT_EQ(-1, num);
}

TEST_F(UtilsTests,
StrToNumWithValidHexadecimalIntegerSucceeds) {
	int num = 0;
	EXPECT_TRUE(strToNum("-0x3E8", num, std::hex));
	EXPECT_EQ(-0x3E8, num);

	num = 0;
	EXPECT_TRUE(strToNum("-0x1", num, std::hex));
	EXPECT_EQ(-0x1, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x0", num, std::hex));
	EXPECT_EQ(0x0, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x1", num, std::hex));
	EXPECT_EQ(0x1, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x3E8", num, std::hex));
	EXPECT_EQ(0x3E8, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x00C", num, std::hex));
	EXPECT_EQ(0x00C, num);
}

TEST_F(UtilsTests,
StrToNumWithInvalidHexadecimalIntegerFails) {
	int num = -1;
	EXPECT_FALSE(strToNum("", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("0x", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("zz", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("0xC something", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("0xCsomething", num, std::hex));
	EXPECT_EQ(-1, num);
}

//
// readUpTo()
//

TEST_F(UtilsTests,
ReadUpToReadsCorrectlyAllCharactersUpToSentinel) {
	std::istringstream input("abcd$");
	std::string readData;

	bool dataReadCorrectly = readUpTo(input, readData, '$');
	ASSERT_TRUE(dataReadCorrectly);
	EXPECT_EQ(readData, "abcd");
}

TEST_F(UtilsTests,
ReadUpToReturnsFalseWhenSentinelIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	bool dataReadCorrectly = readUpTo(input, readData, '$');
	EXPECT_FALSE(dataReadCorrectly);
}

TEST_F(UtilsTests,
ReadUpToStoresReadCharsEvenWhenSentinelIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	readUpTo(input, readData, '$');
	EXPECT_EQ("abcd", readData);
}

//
// readUntil()
//

TEST_F(UtilsTests,
ReadUntilReadsCorrectlyAllCharactersIncludingLast) {
	std::istringstream input("abcd$");
	std::string readData;

	bool dataReadCorrectly = readUntil(input, readData, '$');
	ASSERT_TRUE(dataReadCorrectly);
	EXPECT_EQ(readData, "abcd$");
}

TEST_F(UtilsTests,
ReadUntilToReturnsFalseWhenLastIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	bool dataReadCorrectly = readUntil(input, readData, '$');
	EXPECT_FALSE(dataReadCorrectly);
}

TEST_F(UtilsTests,
ReadUntilStoresReadCharsEvenWhenLastIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	readUntil(input, readData, '$');
	EXPECT_EQ("abcd", readData);
}

//
// clear()
//

template <class ContainerType>
void scenarioClearEmptiesContainer(ContainerType &container) {
	clear(container);
	EXPECT_TRUE(container.empty());
}

TEST_F(UtilsTests,
ClearOnVectorClearsIt) {
	std::vector<int> v(100, 0);

	ADD_SCOPED_TRACE;
	scenarioClearEmptiesContainer(v);
}

TEST_F(UtilsTests,
ClearOnQueueClearsIt) {
	std::queue<int> q;
	q.push(1);
	q.push(2);
	q.push(3);

	ADD_SCOPED_TRACE;
	scenarioClearEmptiesContainer(q);
}

TEST_F(UtilsTests,
ClearOnStackClearsIt) {
	std::stack<int> s;
	s.push(1);
	s.push(2);
	s.push(3);

	ADD_SCOPED_TRACE;
	scenarioClearEmptiesContainer(s);
}

//
// replace()
//

TEST_F(UtilsTests,
ReplaceDoesNotPerformAnyReplacementWhenStringIsEmpty) {
	EXPECT_EQ("", replace("", 'x', "X"));
}

TEST_F(UtilsTests,
ReplaceDoesNotPerformAnyReplacementWhenCharDoesNotAppearInString) {
	EXPECT_EQ("abcd", replace("abcd", 'x', "X"));
}

TEST_F(UtilsTests,
ReplaceCorrectlyReplacesCharInStringIfItOccursOnce) {
	EXPECT_EQ("Abcd", replace("abcd", 'a', "A"));
}

TEST_F(UtilsTests,
ReplaceCorrectlyReplacesCharInStringIfItOccursTwice) {
	EXPECT_EQ("AbcA", replace("abca", 'a', "A"));
}

TEST_F(UtilsTests,
ReplaceCorrectlyReplacesCharInStringWhenWithWhatIsLongerThanOneChar) {
	EXPECT_EQ("XXXXbcXXXX", replace("abca", 'a', "XXXX"));
}

TEST_F(UtilsTests,
ReplaceDeletesCharsInStringWhenWithWhatIsEmpty) {
	EXPECT_EQ("bc", replace("abca", 'a', ""));
}

} // namespace tests
} // namespace bencoding
<commit_msg>Utils: Add tests for the handling of error/EOF inputs by the read functions.<commit_after>/**
* @file      UtilsTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license   BSD, see the @c LICENSE file for more details
* @brief     Tests for the utilities.
*/

#include <gtest/gtest.h>

#include "TestUtils.h"
#include "Utils.h"

namespace bencoding {
namespace tests {

using namespace testing;

class UtilsTests: public Test {};

//
// strToNum()
//

TEST_F(UtilsTests,
StrToNumWithValidDecimalIntegerSucceeds) {
	int num = 0;
	EXPECT_TRUE(strToNum("-1000", num, std::dec));
	EXPECT_EQ(-1000, num);

	num = 0;
	EXPECT_TRUE(strToNum("-1", num, std::dec));
	EXPECT_EQ(-1, num);

	num = 0;
	EXPECT_TRUE(strToNum("0", num, std::dec));
	EXPECT_EQ(0, num);

	num = 0;
	EXPECT_TRUE(strToNum("1", num, std::dec));
	EXPECT_EQ(1, num);

	num = 0;
	EXPECT_TRUE(strToNum("1000", num, std::dec));
	EXPECT_EQ(1000, num);

	num = 0;
	EXPECT_TRUE(strToNum("0000", num, std::dec));
	EXPECT_EQ(0, num);

	num = 0;
	EXPECT_TRUE(strToNum("0003", num, std::dec));
	EXPECT_EQ(3, num);
}

TEST_F(UtilsTests,
StrToNumWithInvalidDecimalIntegerFails) {
	int num = -1;
	EXPECT_FALSE(strToNum("", num, std::dec));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("zzz", num, std::dec));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("13 something", num, std::dec));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("13something", num, std::dec));
	EXPECT_EQ(-1, num);
}

TEST_F(UtilsTests,
StrToNumWithValidHexadecimalIntegerSucceeds) {
	int num = 0;
	EXPECT_TRUE(strToNum("-0x3E8", num, std::hex));
	EXPECT_EQ(-0x3E8, num);

	num = 0;
	EXPECT_TRUE(strToNum("-0x1", num, std::hex));
	EXPECT_EQ(-0x1, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x0", num, std::hex));
	EXPECT_EQ(0x0, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x1", num, std::hex));
	EXPECT_EQ(0x1, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x3E8", num, std::hex));
	EXPECT_EQ(0x3E8, num);

	num = 0;
	EXPECT_TRUE(strToNum("0x00C", num, std::hex));
	EXPECT_EQ(0x00C, num);
}

TEST_F(UtilsTests,
StrToNumWithInvalidHexadecimalIntegerFails) {
	int num = -1;
	EXPECT_FALSE(strToNum("", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("0x", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("zz", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("0xC something", num, std::hex));
	EXPECT_EQ(-1, num);

	num = -1;
	EXPECT_FALSE(strToNum("0xCsomething", num, std::hex));
	EXPECT_EQ(-1, num);
}

//
// readUpTo()
//

TEST_F(UtilsTests,
ReadUpToReadsCorrectlyAllCharactersUpToSentinel) {
	std::istringstream input("abcd$");
	std::string readData;

	bool dataReadCorrectly = readUpTo(input, readData, '$');
	ASSERT_TRUE(dataReadCorrectly);
	EXPECT_EQ(readData, "abcd");
}

TEST_F(UtilsTests,
ReadUpToReturnsFalseWhenSentinelIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	bool dataReadCorrectly = readUpTo(input, readData, '$');
	EXPECT_FALSE(dataReadCorrectly);
}

TEST_F(UtilsTests,
ReadUpToStoresReadCharsEvenWhenSentinelIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	readUpTo(input, readData, '$');
	EXPECT_EQ("abcd", readData);
}

TEST_F(UtilsTests,
ReadUpToReturnsFalseWhenInputIsInErrorState) {
	std::istringstream input("abcd$");
	std::string readData;

	putIntoErrorState(input);
	EXPECT_FALSE(readUpTo(input, readData, '$'));
}

TEST_F(UtilsTests,
ReadUpToDoesNotReadAnyDataWhenInputIsInErrorState) {
	std::istringstream input("abc$");
	std::string readData;

	putIntoErrorState(input);
	readUpTo(input, readData, '$');
	EXPECT_EQ("", readData);
}

TEST_F(UtilsTests,
ReadUpToReturnsFalseWhenInputIsInEOFState) {
	std::istringstream input("abcd$");
	std::string readData;

	putIntoEOFState(input);
	EXPECT_FALSE(readUpTo(input, readData, '$'));
}

TEST_F(UtilsTests,
ReadUpToDoesNotReadAnyDataWhenInputIsInEOFState) {
	std::istringstream input("abcd$");
	std::string readData;

	putIntoEOFState(input);
	readUpTo(input, readData, '$');
	EXPECT_EQ("", readData);
}

//
// readUntil()
//

TEST_F(UtilsTests,
ReadUntilReadsCorrectlyAllCharactersIncludingLast) {
	std::istringstream input("abcd$");
	std::string readData;

	bool dataReadCorrectly = readUntil(input, readData, '$');
	ASSERT_TRUE(dataReadCorrectly);
	EXPECT_EQ(readData, "abcd$");
}

TEST_F(UtilsTests,
ReadUntilToReturnsFalseWhenLastIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	bool dataReadCorrectly = readUntil(input, readData, '$');
	EXPECT_FALSE(dataReadCorrectly);
}

TEST_F(UtilsTests,
ReadUntilStoresReadCharsEvenWhenLastIsNotFound) {
	std::istringstream input("abcd");
	std::string readData;

	readUntil(input, readData, '$');
	EXPECT_EQ("abcd", readData);
}

TEST_F(UtilsTests,
ReadUntilDoesNotReadAnyDataWhenInputIsInErrorState) {
	std::istringstream input("abcd$");
	std::string readData;

	putIntoErrorState(input);
	readUntil(input, readData, '$');
	EXPECT_EQ("", readData);
}

TEST_F(UtilsTests,
ReadUntilReturnsFalseWhenInputIsInEOFState) {
	std::istringstream input("abc$");
	std::string readData;

	putIntoEOFState(input);
	EXPECT_FALSE(readUntil(input, readData, '$'));
}

TEST_F(UtilsTests,
ReadUntilDoesNotReadAnyDataWhenInputIsInEOFState) {
	std::istringstream input("abcd$");
	std::string readData;

	putIntoEOFState(input);
	readUntil(input, readData, '$');
	EXPECT_EQ("", readData);
}

//
// clear()
//

template <class ContainerType>
void scenarioClearEmptiesContainer(ContainerType &container) {
	clear(container);
	EXPECT_TRUE(container.empty());
}

TEST_F(UtilsTests,
ClearOnVectorClearsIt) {
	std::vector<int> v(100, 0);

	ADD_SCOPED_TRACE;
	scenarioClearEmptiesContainer(v);
}

TEST_F(UtilsTests,
ClearOnQueueClearsIt) {
	std::queue<int> q;
	q.push(1);
	q.push(2);
	q.push(3);

	ADD_SCOPED_TRACE;
	scenarioClearEmptiesContainer(q);
}

TEST_F(UtilsTests,
ClearOnStackClearsIt) {
	std::stack<int> s;
	s.push(1);
	s.push(2);
	s.push(3);

	ADD_SCOPED_TRACE;
	scenarioClearEmptiesContainer(s);
}

//
// replace()
//

TEST_F(UtilsTests,
ReplaceDoesNotPerformAnyReplacementWhenStringIsEmpty) {
	EXPECT_EQ("", replace("", 'x', "X"));
}

TEST_F(UtilsTests,
ReplaceDoesNotPerformAnyReplacementWhenCharDoesNotAppearInString) {
	EXPECT_EQ("abcd", replace("abcd", 'x', "X"));
}

TEST_F(UtilsTests,
ReplaceCorrectlyReplacesCharInStringIfItOccursOnce) {
	EXPECT_EQ("Abcd", replace("abcd", 'a', "A"));
}

TEST_F(UtilsTests,
ReplaceCorrectlyReplacesCharInStringIfItOccursTwice) {
	EXPECT_EQ("AbcA", replace("abca", 'a', "A"));
}

TEST_F(UtilsTests,
ReplaceCorrectlyReplacesCharInStringWhenWithWhatIsLongerThanOneChar) {
	EXPECT_EQ("XXXXbcXXXX", replace("abca", 'a', "XXXX"));
}

TEST_F(UtilsTests,
ReplaceDeletesCharsInStringWhenWithWhatIsEmpty) {
	EXPECT_EQ("bc", replace("abca", 'a', ""));
}

} // namespace tests
} // namespace bencoding
<|endoftext|>


<commit_before>#include <base/tensor.h>
#include <iostream>

DeclException2 (Exc1,
		int, int,
		<< "arg1=" << arg1 << " arg2=" << arg2);

int main () {
  double a[3][3] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}};
  double b[3][3] = {{25,31,37}, {45,57,69}, {75,96,117}};

  try
    {
      ThrowIfNot (1>2, Exc1(1,2));
      cerr << "11111111111111111111";
    }
  catch (exception &e)
    {
      cerr << e.what();
      cerr << "33333333333333333333";
    };

  const unsigned int dim=3;
  Tensor<2,dim> t(a);
  Tensor<2,dim> tt;
  Tensor<2,dim> result(b);

  cout << "t=" << endl;
  for (unsigned int i=0; i<dim; ++i)
    {
      for (unsigned int j=0; j<dim; ++j)
	cout << t[i][j] << ' ';
      cout << endl;
    };
  cout << endl;

  contract (tt,t,t);

  cout << "tt=" << endl;
  for (unsigned int i=0; i<dim; ++i)
    {
      for (unsigned int j=0; j<dim; ++j)
	cout << tt[i][j] << ' ';
      cout << endl;
    };
  cout << endl;

  if (tt==result)
    {
      cout << "Result OK." << endl;
      return 0;
    }
  else
    {
      cout << "Result WRONG!" << endl;
      return 1;
    };
};
<commit_msg>Restore initial state, after abusing this testcase as a testbed for the new exception mechanism.<commit_after>#include <base/tensor.h>
#include <iostream>

int main () {
  double a[3][3] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}};
  double b[3][3] = {{25,31,37}, {45,57,69}, {75,96,117}};

  const unsigned int dim=3;
  Tensor<2,dim> t(a);
  Tensor<2,dim> tt;
  Tensor<2,dim> result(b);

  cout << "t=" << endl;
  for (unsigned int i=0; i<dim; ++i)
    {
      for (unsigned int j=0; j<dim; ++j)
	cout << t[i][j] << ' ';
      cout << endl;
    };
  cout << endl;

  contract (tt,t,t);

  cout << "tt=" << endl;
  for (unsigned int i=0; i<dim; ++i)
    {
      for (unsigned int j=0; j<dim; ++j)
	cout << tt[i][j] << ' ';
      cout << endl;
    };
  cout << endl;

  if (tt==result)
    {
      cout << "Result OK." << endl;
      return 0;
    }
  else
    {
      cout << "Result WRONG!" << endl;
      return 1;
    };
};
<|endoftext|>


<commit_before>#include "map.h"
#include "lion.h"
#include "rabbit.h"
#include "wolf.h"

map::map(int w, int h, int lchance, int rchance, int tchance, long maxtick)
{
    //ctor
    tick_count=0;
    lion_chance=lchance;
    rabbit_chance=rchance;
    tree_chance=tchance;
    height=h;
    width=w;
    max_ticks=maxtick;
    grid = new map_object*[h];
    for(int i=0; i<h; i++)
    {
        grid[i] = new map_object[w];
        for(int j=0; j<w; j++) if(i!=h/2+1 || j!=w/2+1)
            {
                grid[i][j] = BLANK;///Shouldn't be necessary
                generate_terrain(i,j);
            }
    }
    grid[h/2+1][w/2+1] = WOLF;
    animals.push_front(new wolf());
}

map::~map()
{
    //dtor
    for(int i=0; i<height; i++) delete grid[i];
    delete[] grid;
    while(!animals.size()>1)
    {
        delete animals.back();
        animals.pop_back();
    }
}
map::map(const map& other)
{
    //"copy" ctor
    tick_count=0;
    lion_chance=other.lion_chance;
    rabbit_chance=other.rabbit_chance;
    tree_chance=other.tree_chance;
    height=other.height;
    width=other.width;
    max_ticks=other.max_ticks;
    grid = new map_object*[height];
    for(int i=0; i<height; i++)
    {
        grid[i] = new map_object[width];
        for(int j=0; j<width; j++) if(i!=height/2+1 && j!=width/2+1)generate_terrain(i,j);
    }
    grid[height/2+1][width/2+1] = WOLF;
    wolf * def = new wolf();
    animals.push_front(def);
}

map& map::operator=(const map& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

void map::generate_terrain(int x,int y)
{
    srand (time(NULL));
    int roll = rand() % 100;
    if(roll<lion_chance)
    {
        grid[x][y] = LION;
        lion * L = new lion;
        coordinate c = {x,y};
        L -> set_location(c);
        animals.push_back(L);
    }
    else if(roll<lion_chance+rabbit_chance)
    {
        grid[x][y] = RABBIT;
        rabbit * R = new rabbit;
        coordinate c = {x,y};
        R -> set_location(c);
        animals.push_back(R);
    }
    else if(roll<lion_chance+rabbit_chance+tree_chance)
    {
        grid[x][y] = TREE;
    }
    else
    {
        grid[x][y] = BLANK;
    }
}

void map::move_map(direction dir)
{
    int x=0;
    int y=0;
    switch(dir) ///Reverse, because if the wolf moved right, the map moves left, etc
    {
    case ::UP:
        y=1;
        break;
    case ::RIGHT:
        x=-1;
        break;
    case ::DOWN:
        y=-1;
        break;
    case ::LEFT:
        x=1;
        break;
    case ::NOWHERE:
        break;
    }
    for(int i=0; i<height; i++)
    {
        for(int j=0; j<width; j++)
        {
            if(i+y<height && i+y>=0)
                if(j+x<width && j+x>=0)
                {
                    coordinate c = {i,j};
                    animal* local = find_animal_by_location(c);
                    c.x=i+y;
                    c.y=j+x;
                    if(local!=NULL) local -> set_location(c);
                    swap(grid[i][j],grid[i+y][j+x]);
                }
        }
    }
}

void map::draw_map()
{
    for(int i=1; i<height-1; i++)
    {
        for(int j=1; j<width-1; j++)
        {
            char token;
            switch(grid[i][j])
            {
            case TREE:
                token='T';
                break;
            case LION:
                token='L';
                break;
            case RABBIT:
                token='R';
                break;
            case WOLF:
                token='W';
                break;
            default:
                token=' ';
            }
            cout << token;
        }
        cout << endl;
    }
}

void map::placewolf(wolf* protag)
{
    delete animals.front();
    animals.pop_front();
    coordinate c = {height/2+1,width/2+1};
    protag -> set_location(c);
    animals.push_front(protag);
}

long map::run(bool show)
{
    wolf * p = (wolf*)(animals.front());
    while(tick_count<max_ticks && !(p->starve()))
    {
        ///Move everyone
        list<animal*>::iterator it;
        coordinate c;
        for (it=animals.begin(); it!=animals.end() ; ++it)
        {
            direction d = (*it) -> act();
            c = (*it) -> get_location();
            int x = c.x;
            int y = c.y;
            int modx=0;
            int mody=0;
            switch(d)
            {
            case UP:
                modx=-1;
                break;
            case DOWN:
                modx=1;
                break;
            case RIGHT:
                mody=1;
                break;
            case LEFT:
                mody=-1;
                break;
            case NOWHERE:
                break;
            }
            if(x==0 || y == 0 || x==height-1 || y==width-1)
            {
                ///If the animal left the map...
                animal * ptr = (*it);
                --it;//This is safe, because the wolf never leaves the map, and is always first in the list
                animals.remove(ptr);
                delete ptr;
            }
            if(modx!=0 || mody!=0)switch(grid[x][y])
                {
                case WOLF:
                    switch(grid[x+modx][y+mody])
                    {
                    case WOLF:
                        cout << "The developer did not account for 2 wolves on the same map!" << endl;
                        break;
                    case RABBIT:
                    {
                        c.x=x+modx;
                        c.y=y+mody;
                        animal * ptr = find_animal_by_location(c);
                        animals.remove(ptr);
                        delete ptr;
                        (*it) -> set_location(c);
                        move_map(d);
                        p -> eat();
                    }
                    break;
                    case LION:
                        ///The Wolf gets himself killed
                        return tick_count;
                    case TREE:
                        break;
                    case BLANK:
                        c.x=x+modx;
                        c.y=y+mody;
                        (*it) -> set_location(c);
                        move_map(d);
                        break;
                    }
                    if(show)
                    {
                        draw_map();
                        cin.ignore();
                    }
                    break;

                case LION:
                    switch(grid[x+modx][y+mody])
                    {
                    case WOLF:
                        ///The wolf has been eaten
                        return tick_count;
                        break;
                    case RABBIT:
                        ///Don't move, you might step on the rabbit!
                        break;
                    case LION:
                        ///Don't move, you'll make the other lion angry
                        break;
                    case TREE:
                        ///The lion hits a tree! Ow!
                        break;
                    case BLANK:
                        c.x=x+modx;
                        c.y=y+mody;
                        (*it) -> set_location(c);
                        break;
                    }

                case RABBIT:
                    switch(grid[x+modx][y+mody])
                    {
                    case WOLF:
                        ///The rabbit sacrificed himself. Should not happen.
                    {
                        p -> eat();
                        animal* ptr=(*it);
                        --it;
                        delete ptr;
                    }
                    break;
                    case RABBIT:
                        ///Don't move, the other rabbit is in the way
                        break;
                    case LION:
                        ///Don't move, you'll make the lion angry!
                        break;
                    case TREE:
                        ///The rabbit hits a tree! Ow!
                        break;
                    case BLANK:
                        c.x=x+modx;
                        c.y=y+mody;
                        (*it) -> set_location(c);
                        break;
                    }
                default:
                    break;
                }
            else if(show && (*it)==p)
            {
                draw_map();
                cin.ignore();
            }
        }
        ///
        p -> grow_hungry();
        generate_edges();
        tick_count++;
    }
    return tick_count;
}

list<coordinate> map::get_all_lions()
{
    list<animal*>::iterator it;
    list<coordinate> lions;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==LION) lions.push_front((*it)->get_location());
    }
    return lions;
}
list<coordinate> map::get_all_rabbits()
{
    list<animal*>::iterator it;
    list<coordinate> rabbits;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==RABBIT) rabbits.push_front((*it)->get_location());
    }
    return rabbits;
}

coordinate map::get_nearest_wolf(coordinate source)
{
    list<animal*>::iterator it;
    int dist=0;
    int mindist=width+height;
    coordinate mindistcoor=source;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==WOLF)
        {
            dist=measure_distance(source,loc);
            if(dist<mindist&&dist!=0)
            {
                mindistcoor=loc;
                mindist=dist;
            }
        }
    }
    return mindistcoor;
}

coordinate map::get_nearest_lion(coordinate source)
{
    list<animal*>::iterator it;
    int dist=0;
    int mindist=width+height;
    coordinate mindistcoor=source;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==RABBIT)
        {
            dist=measure_distance(source,loc);
            if(dist<mindist&&dist!=0)
            {
                mindistcoor=loc;
                mindist=dist;
            }
        }
    }
    return mindistcoor;
}

coordinate map::get_nearest_rabbit(coordinate source)
{
    list<animal*>::iterator it;
    int dist=0;
    int mindist=width+height;
    coordinate mindistcoor=source;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==RABBIT)
        {
            dist=measure_distance(source,loc);
            if(dist<mindist&&dist!=0)
            {
                mindistcoor=loc;
                mindist=dist;
            }
        }
    }
    return mindistcoor;
}

map_object** map::get_grid()
{
    return grid;
}

int map::measure_distance(coordinate source,coordinate target)
{
    int distx = pow(source.x-target.x,2);
    int disty = pow(source.y-target.y,2);
    int result = sqrt(distx+disty);
    return result;
}

void map::generate_edges()
{
    for(int i=0; i<height; i++)
    {
        for(int j=0; j<width; j++)
        {
            if(i==height-1 || j==width-1 || i==0 || j==0) generate_terrain(i,j);
        }
    }
}

animal* map::find_animal_by_location(coordinate c)
{
    list<animal*>::iterator it;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        if((*it)->get_location().x==c.x && (*it)->get_location().y==c.y ) return (*it);
    }
    return NULL;
}
<commit_msg>Small fix<commit_after>#include "map.h"
#include "lion.h"
#include "rabbit.h"
#include "wolf.h"

map::map(int w, int h, int lchance, int rchance, int tchance, long maxtick)
{
    //ctor
    tick_count=0;
    lion_chance=lchance;
    rabbit_chance=rchance;
    tree_chance=tchance;
    height=h;
    width=w;
    max_ticks=maxtick;
    grid = new map_object*[h];
    for(int i=0; i<h; i++)
    {
        grid[i] = new map_object[w];
        for(int j=0; j<w; j++) if(i!=h/2+1 || j!=w/2+1)
            {
                grid[i][j] = BLANK;///Shouldn't be necessary
                generate_terrain(i,j);
            }
    }
    grid[h/2+1][w/2+1] = WOLF;
    animals.push_front(new wolf());
}

map::~map()
{
    //dtor
    for(int i=0; i<height; i++) delete grid[i];
    delete[] grid;
    while(animals.size()>1)
    {
        ///Once size()==1, only the wolf is left, and it is not deleted
        delete animals.back();
        animals.pop_back();
    }
}
map::map(const map& other)
{
    //"copy" ctor
    tick_count=0;
    lion_chance=other.lion_chance;
    rabbit_chance=other.rabbit_chance;
    tree_chance=other.tree_chance;
    height=other.height;
    width=other.width;
    max_ticks=other.max_ticks;
    grid = new map_object*[height];
    for(int i=0; i<height; i++)
    {
        grid[i] = new map_object[width];
        for(int j=0; j<width; j++) if(i!=height/2+1 && j!=width/2+1)generate_terrain(i,j);
    }
    grid[height/2+1][width/2+1] = WOLF;
    wolf * def = new wolf();
    animals.push_front(def);
}

map& map::operator=(const map& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

void map::generate_terrain(int x,int y)
{
    srand (time(NULL));
    int roll = rand() % 100;
    if(roll<lion_chance)
    {
        grid[x][y] = LION;
        lion * L = new lion;
        coordinate c = {x,y};
        L -> set_location(c);
        animals.push_back(L);
    }
    else if(roll<lion_chance+rabbit_chance)
    {
        grid[x][y] = RABBIT;
        rabbit * R = new rabbit;
        coordinate c = {x,y};
        R -> set_location(c);
        animals.push_back(R);
    }
    else if(roll<lion_chance+rabbit_chance+tree_chance)
    {
        grid[x][y] = TREE;
    }
    else
    {
        grid[x][y] = BLANK;
    }
}

void map::move_map(direction dir)
{
    int x=0;
    int y=0;
    switch(dir) ///Reverse, because if the wolf moved right, the map moves left, etc
    {
    case ::UP:
        y=1;
        break;
    case ::RIGHT:
        x=-1;
        break;
    case ::DOWN:
        y=-1;
        break;
    case ::LEFT:
        x=1;
        break;
    case ::NOWHERE:
        break;
    }
    for(int i=0; i<height; i++)
    {
        for(int j=0; j<width; j++)
        {
            if(i+y<height && i+y>=0)
                if(j+x<width && j+x>=0)
                {
                    coordinate c = {i,j};
                    animal* local = find_animal_by_location(c);
                    c.x=i+y;
                    c.y=j+x;
                    if(local!=NULL) local -> set_location(c);
                    swap(grid[i][j],grid[i+y][j+x]);
                }
        }
    }
}

void map::draw_map()
{
    for(int i=1; i<height-1; i++)
    {
        for(int j=1; j<width-1; j++)
        {
            char token;
            switch(grid[i][j])
            {
            case TREE:
                token='T';
                break;
            case LION:
                token='L';
                break;
            case RABBIT:
                token='R';
                break;
            case WOLF:
                token='W';
                break;
            default:
                token=' ';
            }
            cout << token;
        }
        cout << endl;
    }
}

void map::placewolf(wolf* protag)
{
    delete animals.front();
    animals.pop_front();
    coordinate c = {height/2+1,width/2+1};
    protag -> set_location(c);
    animals.push_front(protag);
}

long map::run(bool show)
{
    wolf * p = (wolf*)(animals.front());
    while(tick_count<max_ticks && !(p->starve()))
    {
        ///Move everyone
        list<animal*>::iterator it;
        coordinate c;
        for (it=animals.begin(); it!=animals.end() ; ++it)
        {
            direction d = (*it) -> act();
            c = (*it) -> get_location();
            int x = c.x;
            int y = c.y;
            int modx=0;
            int mody=0;
            switch(d)
            {
            case UP:
                modx=-1;
                break;
            case DOWN:
                modx=1;
                break;
            case RIGHT:
                mody=1;
                break;
            case LEFT:
                mody=-1;
                break;
            case NOWHERE:
                break;
            }
            if(x==0 || y == 0 || x==height-1 || y==width-1)
            {
                ///If the animal left the map...
                animal * ptr = (*it);
                --it;//This is safe, because the wolf never leaves the map, and is always first in the list
                animals.remove(ptr);
                delete ptr;
            }
            if(modx!=0 || mody!=0)switch(grid[x][y])
                {
                case WOLF:
                    switch(grid[x+modx][y+mody])
                    {
                    case WOLF:
                        cout << "The developer did not account for 2 wolves on the same map!" << endl;
                        break;
                    case RABBIT:
                    {
                        c.x=x+modx;
                        c.y=y+mody;
                        animal * ptr = find_animal_by_location(c);
                        animals.remove(ptr);
                        delete ptr;
                        (*it) -> set_location(c);
                        move_map(d);
                        p -> eat();
                    }
                    break;
                    case LION:
                        ///The Wolf gets himself killed
                        return tick_count;
                    case TREE:
                        break;
                    case BLANK:
                        c.x=x+modx;
                        c.y=y+mody;
                        (*it) -> set_location(c);
                        move_map(d);
                        break;
                    }
                    if(show)
                    {
                        draw_map();
                        cin.ignore();
                    }
                    break;

                case LION:
                    switch(grid[x+modx][y+mody])
                    {
                    case WOLF:
                        ///The wolf has been eaten
                        return tick_count;
                        break;
                    case RABBIT:
                        ///Don't move, you might step on the rabbit!
                        break;
                    case LION:
                        ///Don't move, you'll make the other lion angry
                        break;
                    case TREE:
                        ///The lion hits a tree! Ow!
                        break;
                    case BLANK:
                        c.x=x+modx;
                        c.y=y+mody;
                        (*it) -> set_location(c);
                        break;
                    }

                case RABBIT:
                    switch(grid[x+modx][y+mody])
                    {
                    case WOLF:
                        ///The rabbit sacrificed himself. Should not happen.
                    {
                        p -> eat();
                        animal* ptr=(*it);
                        --it;
                        delete ptr;
                    }
                    break;
                    case RABBIT:
                        ///Don't move, the other rabbit is in the way
                        break;
                    case LION:
                        ///Don't move, you'll make the lion angry!
                        break;
                    case TREE:
                        ///The rabbit hits a tree! Ow!
                        break;
                    case BLANK:
                        c.x=x+modx;
                        c.y=y+mody;
                        (*it) -> set_location(c);
                        break;
                    }
                default:
                    break;
                }
            else if(show && (*it)==p)
            {
                draw_map();
                cin.ignore();
            }
        }
        ///
        p -> grow_hungry();
        generate_edges();
        tick_count++;
    }
    return tick_count;
}

list<coordinate> map::get_all_lions()
{
    list<animal*>::iterator it;
    list<coordinate> lions;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==LION) lions.push_front((*it)->get_location());
    }
    return lions;
}
list<coordinate> map::get_all_rabbits()
{
    list<animal*>::iterator it;
    list<coordinate> rabbits;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==RABBIT) rabbits.push_front((*it)->get_location());
    }
    return rabbits;
}

coordinate map::get_nearest_wolf(coordinate source)
{
    list<animal*>::iterator it;
    int dist=0;
    int mindist=width+height;
    coordinate mindistcoor=source;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==WOLF)
        {
            dist=measure_distance(source,loc);
            if(dist<mindist&&dist!=0)
            {
                mindistcoor=loc;
                mindist=dist;
            }
        }
    }
    return mindistcoor;
}

coordinate map::get_nearest_lion(coordinate source)
{
    list<animal*>::iterator it;
    int dist=0;
    int mindist=width+height;
    coordinate mindistcoor=source;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==RABBIT)
        {
            dist=measure_distance(source,loc);
            if(dist<mindist&&dist!=0)
            {
                mindistcoor=loc;
                mindist=dist;
            }
        }
    }
    return mindistcoor;
}

coordinate map::get_nearest_rabbit(coordinate source)
{
    list<animal*>::iterator it;
    int dist=0;
    int mindist=width+height;
    coordinate mindistcoor=source;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        coordinate loc = (*it)->get_location();
        if(grid[loc.x][loc.y]==RABBIT)
        {
            dist=measure_distance(source,loc);
            if(dist<mindist&&dist!=0)
            {
                mindistcoor=loc;
                mindist=dist;
            }
        }
    }
    return mindistcoor;
}

map_object** map::get_grid()
{
    return grid;
}

int map::measure_distance(coordinate source,coordinate target)
{
    int distx = pow(source.x-target.x,2);
    int disty = pow(source.y-target.y,2);
    int result = sqrt(distx+disty);
    return result;
}

void map::generate_edges()
{
    for(int i=0; i<height; i++)
    {
        for(int j=0; j<width; j++)
        {
            if(i==height-1 || j==width-1 || i==0 || j==0) generate_terrain(i,j);
        }
    }
}

animal* map::find_animal_by_location(coordinate c)
{
    list<animal*>::iterator it;
    for (it=animals.begin(); it!=animals.end() ; ++it)
    {
        if((*it)->get_location().x==c.x && (*it)->get_location().y==c.y ) return (*it);
    }
    return NULL;
}
<|endoftext|>


<commit_before>#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <functional>
#include <random>
#include <vector>
#include <string>

#include <gauss_multi.h>
#include <gp.h>

using namespace std;
typedef unsigned int uint;

// Random engine to use throughout
default_random_engine gen;

// How many functions to sample at each step
int n_samp = 5;

void to_tikz(vector<vector<double>> X, vector<vector<double>> Y, string fname)
{
	assert(X.size() == Y.size());
	FILE *f = fopen(fname.c_str(), "w");

	// Define colours (TODO-someday: make this parametrised...)
	fprintf(f, "\\definecolor{mycolor0}{rgb}{0.00000,0.44700,0.74100}%%\n");
	fprintf(f, "\\definecolor{mycolor1}{rgb}{0.85000,0.32500,0.09800}%%\n");
	fprintf(f, "\\definecolor{mycolor2}{rgb}{0.92900,0.69400,0.12500}%%\n");
	fprintf(f, "\\definecolor{mycolor3}{rgb}{0.49400,0.18400,0.55600}%%\n");
	fprintf(f, "\\definecolor{mycolor4}{rgb}{0.46600,0.67400,0.18800}%%\n");

	// Begin picture
	fprintf(f, "\\begin{tikzpicture}[very thick]\n");
	// Begin axis (with all parameters)
	fprintf(f, "\\begin{axis}[very thick, width=6.028in, height=4.754in,\n");
	fprintf(f, "scale only axis, xmin=-5, xmax=5, ymin=-5, ymax=5,\n");
	fprintf(f, "axis background/.style={fill=white}]\n");

	// Add plots
	for (uint i=0;i<X.size();i++)
	{
		assert(X[i].size() == Y[i].size());
		fprintf(f, "\\addplot[color=mycolor%d, solid] table[row sep=crcr]{%%\n", i);
		for (uint j=0;j<X[i].size();j++)
		{
			fprintf(f, "%.10lf %.10lf\\\\\n", X[i][j], Y[i][j]);
		}
		fprintf(f, "};\n");
	}

	fprintf(f, "\\end{axis}\n");
	fprintf(f, "\\end{tikzpicture}\n");

	fclose(f);
}

int main()
{
	// Create a new Gaussian process...
	// use zero-mean, squared-exponential covariance (hyperparam l = 0.75), no noise.
	auto m = [](double) { return 0; };
	auto k = [](double x, double y) { return exp(-(x - y) * (x - y) / (2.0 * 0.75 * 0.75)); };
	GP gp(m, k, 0.0);

	gp.push(-3.0, 0.0);
	//gp.push(0.0, 1.0);
	//gp.push(2.0, -1.0);
	//gp.push(4.0, 2.0);

	// points to be used to plot lines
	vector<double> xs;
	for (double x=-5.0;x<=5.0;x+=0.01) xs.push_back(x);

	// Sample the prior
	vector<double> mu = gp.get_means(xs);
	vector<vector<double>> Sigma = gp.get_covar(xs);

	MultiGaussian N(gen, mu, Sigma);

	vector<vector<double>> Xs(n_samp, xs);
	vector<vector<double>> Ys(n_samp);

	for (int i=0;i<n_samp;i++)
	{
		Ys[i] = N.sample();
	}

	to_tikz(Xs, Ys, "test.tex");

	return 0;
}
<commit_msg>New demo... just plot mean +- 2sigma if too big<commit_after>#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <functional>
#include <random>
#include <vector>
#include <string>

#include <gauss_multi.h>
#include <gp.h>

using namespace std;
typedef unsigned int uint;

// Random engine to use throughout
default_random_engine gen;

// How many functions to sample at each step
int n_samp = 5;

void to_tikz(vector<vector<double>> X, vector<vector<double>> Y, vector<vector<double>> Xmss, vector<vector<double>> mss, string fname)
{
	assert(X.size() == Y.size());
	FILE *f = fopen(fname.c_str(), "w");

	fprintf(f, "\\usepgfplotslibrary{fillbetween}\n");

	// Define colours (TODO-someday: make this parametrised...)
	fprintf(f, "\\definecolor{mycolor0}{rgb}{0.00000,0.44700,0.74100}%%\n");
	fprintf(f, "\\definecolor{mycolor1}{rgb}{0.85000,0.32500,0.09800}%%\n");
	fprintf(f, "\\definecolor{mycolor2}{rgb}{0.92900,0.69400,0.12500}%%\n");
	fprintf(f, "\\definecolor{mycolor3}{rgb}{0.49400,0.18400,0.55600}%%\n");
	fprintf(f, "\\definecolor{mycolor4}{rgb}{0.46600,0.67400,0.18800}%%\n");

	// Begin picture
	fprintf(f, "\\begin{tikzpicture}[very thick]\n");
	// Begin axis (with all parameters)
	fprintf(f, "\\begin{axis}[very thick, width=10.028in, height=4.754in,\n");
	fprintf(f, "scale only axis, xmin=-5, xmax=5, ymin=-5, ymax=5,\n");
	fprintf(f, "axis background/.style={fill=white}]\n");

		// plot mean function
	assert(Xmss[0].size() == mss[0].size());
	fprintf(f, "\\addplot[color=black, solid] table[row sep=crcr]{%%\n");
	for (uint j=0;j<Xmss[0].size();j++)
	{
		fprintf(f, "%.10lf %.10lf\\\\\n", Xmss[0][j], mss[0][j]);
	}
	fprintf(f, "};\n");

	// plot +- two sigma
	assert(Xmss[1].size() == mss[1].size());
	fprintf(f, "\\addplot[color=gray, dashed, name path=F] table[row sep=crcr]{%%\n");
	for (uint j=0;j<Xmss[1].size();j++)
	{
		fprintf(f, "%.10lf %.10lf\\\\\n", Xmss[1][j], mss[1][j]);
	}
	fprintf(f, "};\n");

	assert(Xmss[2].size() == mss[2].size());
	fprintf(f, "\\addplot[color=gray, dashed, name path=G] table[row sep=crcr]{%%\n");
	for (uint j=0;j<Xmss[2].size();j++)
	{
		fprintf(f, "%.10lf %.10lf\\\\\n", Xmss[2][j], mss[2][j]);
	}
	fprintf(f, "};\n");

	// fill in between
	fprintf(f, "\\addplot[gray] fill between[of=F and G];\n");

	// Add plots
	for (uint i=0;i<X.size();i++)
	{
		assert(X[i].size() == Y[i].size());
		fprintf(f, "\\addplot[color=mycolor%d, solid] table[row sep=crcr]{%%\n", i);
		for (uint j=0;j<X[i].size();j++)
		{
			fprintf(f, "%.10lf %.10lf\\\\\n", X[i][j], Y[i][j]);
		}
		fprintf(f, "};\n");
	}

	fprintf(f, "\\end{axis}\n");
	fprintf(f, "\\end{tikzpicture}\n");

	fclose(f);
}

int main()
{
	// Create a new Gaussian process...
	// use zero-mean, squared-exponential covariance (hyperparam l = 0.75), no noise.
	auto m = [](double) { return 0; };
	auto k = [](double x, double y) { return exp(-(x - y) * (x - y) / (2.0 * 0.75 * 0.75)); };
	GP gp(m, k, 0.0);

	gp.push(-3.0, 0.0);
	//gp.push(0.0, 1.0);
	gp.push(2.0, -1.0);
	//gp.push(4.0, 2.0);

	// points to be used to plot lines
	vector<double> xs;
	for (double x=-5.0;x<=5.0;x+=0.01) xs.push_back(x);

	// Sample the prior
	vector<double> mu = gp.get_means(xs);
	vector<vector<double>> Sigma = gp.get_covar(xs);

	MultiGaussian N(gen, mu, Sigma);

	vector<vector<double>> Xs(n_samp, xs);
	vector<vector<double>> Ys(n_samp);

	for (int i=0;i<n_samp;i++)
	{
		Ys[i] = N.sample();
	}

	vector<vector<double>> X(3, xs);
	vector<vector<double>> mss(3);

	for (uint i=0;i<xs.size();i++)
	{
		double mu = gp.get_means({xs[i]})[0];
		double std = sqrt(gp.get_covar({xs[i]})[0][0]);
		mss[0].push_back(mu);
		mss[1].push_back(mu - 2 * std);
		mss[2].push_back(mu + 2 * std);
	}

	to_tikz(Xs, Ys, X, mss, "test1.tex");

	// Running into numerical issues for sampling more conditioned posteriors... just plot the mean +- 2 sigma :)

	gp.push(0.0, 1.0);
	gp.push(4.0, 2.0);

	for (uint i=0;i<xs.size();i++)
	{
		double mu = gp.get_means({xs[i]})[0];
		double std = sqrt(gp.get_covar({xs[i]})[0][0]);
		mss[0][i] = mu;
		mss[1][i] = mu - 2 * std;
		mss[2][i] = mu + 2 * std;
	}

	to_tikz({}, {}, X, mss, "test2.tex");

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>I don't know when or how this typo happened. oop<commit_after><|endoftext|>


<commit_before>/*
   This file is part of INDDGO.

   Copyright (C) 2012, Oak Ridge National Laboratory

   This product includes software produced by UT-Battelle, LLC under Contract No.
   DE-AC05-00OR22725 with the Department of Energy.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the New BSD 3-clause software license (LICENSE).

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   LICENSE for more details.

   For more information please contact the INDDGO developers at:
   inddgo-info@googlegroups.com

 */

#include "GraphDecomposition.h"
#include "GraphProperties.h"
#include "Log.h"
#include "VertexWeightedGraph.h"
#include "GraphException.h"
#include "GraphReader.h"
#include "GraphWriter.h"
#include <numeric>
#include <ctime>

using namespace std;

void usage(const char *s){
    fprintf(stderr,"Usage: %s filename\n",s);
}

int main(int argc, char **argv){
    // Check for a cry for help
    if((argc == 1) || ((argc == 2) && (strcmp(argv[1],"-h") == 0)) || ((argc == 2) && (strcmp(argv[1],"--help") == 0))
       || ((argc == 2) && (strcmp(argv[1],"--h") == 0) ) ){
        usage(argv[0]);
        exit(-1);
    }

    Graph::Graph *g;
    int seed = 0;
    int sum;

    clock_t begin, end;

    Graph::GraphProperties prop;
    Graph::GraphReader ngr;

    // Create the graph object
    g = new Graph::Graph();

    // read the graph from the filename, assume it is an edgelist
    ngr.read_graph(g, argv[1], "Edge", false);
    printf("Read %d vertices and %d edges\n", g->get_num_nodes(), g->get_num_edges());

    printf("Simplifying graph\n");
    begin = clock();
    prop.make_simple(g);
    end = clock();
    printf("Time: %lf\n", double(end - begin) / CLOCKS_PER_SEC);
    printf("After simplification: %d vertices and %d edges\n", g->get_num_nodes(), g->get_num_edges());

    //Now, do our calculations
    vector<long int> triangles(g->get_num_nodes(), 0);

    printf("Calculating triangles using compact-forward method\n");
    begin = clock();
    prop.all_triangles_compact_forward(g, triangles);
    end = clock();
    sum = std::accumulate(triangles.begin(), triangles.end(), 0);
    printf("Total triangles (compact-forward): %d\n", sum);
    printf("Time: %lf\n", double(end - begin) / CLOCKS_PER_SEC);

    triangles.assign(g->get_num_nodes(), 0);
    printf("Calculating triangles using edge-listing method\n");
    begin = clock();
    prop.all_triangles_edge_listing(g, triangles);
    end = clock();
    sum = std::accumulate(triangles.begin(), triangles.end(), 0);
    printf("Total triangles (edge-listing): %d (%d)\n", sum / 3, sum);
    printf("Time: %lf\n", double(end - begin) / CLOCKS_PER_SEC);

    double g_cc, a_cc;
    vector<double> l_cc;
    prop.clustering_coefficients(g, g_cc, a_cc, l_cc);

    printf("Local CCs:");
    int i;
    for(i = 0; i < g->get_num_nodes(); i++){
        printf(" %d:%lf",i,l_cc[i]);
    }
    printf("\n");

    printf("Global cc: %lf\nAvg cc: %lf", g_cc, a_cc);

    delete g;

    return 0;
} // main

<commit_msg>add timings to count-tri<commit_after>/*
   This file is part of INDDGO.

   Copyright (C) 2012, Oak Ridge National Laboratory

   This product includes software produced by UT-Battelle, LLC under Contract No.
   DE-AC05-00OR22725 with the Department of Energy.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the New BSD 3-clause software license (LICENSE).

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   LICENSE for more details.

   For more information please contact the INDDGO developers at:
   inddgo-info@googlegroups.com

 */

#include "GraphDecomposition.h"
#include "GraphProperties.h"
#include "Log.h"
#include "VertexWeightedGraph.h"
#include "GraphException.h"
#include "GraphReader.h"
#include "GraphWriter.h"
#include <numeric>
#include <ctime>
#include <sys/time.h>
#include <stdint.h>

using namespace std;

void usage(const char *s){
    fprintf(stderr,"Usage: %s filename\n",s);
}

uint64_t diff_timeval(struct timeval begin, struct timeval end){
    uint64_t begin_us, end_us;

    begin_us = begin.tv_usec + 100000*begin.tv_sec;
    end_us = end.tv_usec + 100000*end.tv_sec;
    return (end_us - begin_us);
}

int main(int argc, char **argv){
    // Check for a cry for help
    if((argc == 1) || ((argc == 2) && (strcmp(argv[1],"-h") == 0)) || ((argc == 2) && (strcmp(argv[1],"--help") == 0))
       || ((argc == 2) && (strcmp(argv[1],"--h") == 0) ) ){
        usage(argv[0]);
        exit(-1);
    }

    Graph::Graph *g;
    int seed = 0;
    int sum;

    clock_t begin, end;
    struct timeval t1, t2;
    uint64_t elapsed;

    Graph::GraphProperties prop;
    Graph::GraphReader ngr;

    // Create the graph object
    g = new Graph::Graph();

    // read the graph from the filename, assume it is an edgelist
    ngr.read_graph(g, argv[1], "Edge", false);
    printf("Read %d vertices and %d edges\n", g->get_num_nodes(), g->get_num_edges());

    printf("Simplifying graph\n");
    begin = clock();
    gettimeofday(&t1, NULL);
    prop.make_simple(g);
    gettimeofday(&t2, NULL);
    end = clock();
    printf("Time: %lf\n", double(end - begin) / CLOCKS_PER_SEC);
    printf("Time (gt): %lf\n", diff_timeval(t1, t2) / 100000.0);
    printf("After simplification: %d vertices and %d edges\n", g->get_num_nodes(), g->get_num_edges());

    //Now, do our calculations
    vector<long int> triangles(g->get_num_nodes(), 0);

    printf("Calculating triangles using compact-forward method\n");
    begin = clock();
    prop.all_triangles_compact_forward(g, triangles);
    end = clock();
    sum = std::accumulate(triangles.begin(), triangles.end(), 0);
    printf("Total triangles (compact-forward): %d\n", sum);
    printf("Time: %lf\n", double(end - begin) / CLOCKS_PER_SEC);

    /*
    triangles.assign(g->get_num_nodes(), 0);
    printf("Calculating triangles using edge-listing method\n");
    begin = clock();
    prop.all_triangles_edge_listing(g, triangles);
    end = clock();
    sum = std::accumulate(triangles.begin(), triangles.end(), 0);
    printf("Total triangles (edge-listing): %d (%d)\n", sum / 3, sum);
    printf("Time: %lf\n", double(end - begin) / CLOCKS_PER_SEC);
*/
   // double g_cc, a_cc;
  //  vector<double> l_cc;
  //  prop.clustering_coefficients(g, g_cc, a_cc, l_cc);

 //   printf("Local CCs:");
  //  int i;
//    for(i = 0; i < g->get_num_nodes(); i++){
 //     printf(" %d:%lf",i,l_cc[i]);
//    }
//   printf("\n");

  //  printf("Global cc: %lf\nAvg cc: %lf", g_cc, a_cc);

    delete g;

    return 0;
} // main

<|endoftext|>


<commit_before><commit_msg>Revert "Temporary: show old staking reward estimation time"<commit_after><|endoftext|>


<commit_before><commit_msg>remove virtual from operator=<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sfxhelp.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: pb $ $Date: 2001-06-21 08:24:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SFX_HELP_HXX
#define _SFX_HELP_HXX

#ifndef _HELP_HXX //autogen
#include <vcl/help.hxx>
#endif

#include <tools/string.hxx>

class SfxHelp_Impl;
class SfxFrame;
class SfxHelp : public Help
{
    String          aTicket;        // for Plugins
    String          aUser;
    String          aLanguageStr;
    String          aCountryStr;
    sal_Bool        bIsDebug;
    SfxHelp_Impl*   pImp;

private:
    virtual BOOL    Start( ULONG nHelpId, const Window* pWindow );
    virtual BOOL    Start( const String& rURL, const Window* pWindow );

    String          GetHelpModuleName_Impl( ULONG nHelpId );
    String          CreateHelpURL_Impl( ULONG nHelpId, const String& rModuleName );

public:

                    SfxHelp();
                    ~SfxHelp();
    void            SetTicket( const String& rTicket )
                    { aTicket = rTicket;}
    void            SetUser( const String& rUser )
                    { aUser = rUser;}

    virtual XubString   GetHelpText( ULONG nHelpId, const Window* pWindow );

    static String       CreateHelpURL( ULONG nHelpId, const String& rModuleName );
    static void         OpenHelpAgent( SfxFrame* pFrame, ULONG nHelpId );
};

#endif // #ifndef _SFX_HELP_HXX

<commit_msg>INTEGRATION: CWS help2 (1.14.542); FILE MERGED 2004/06/08 13:39:05 cd 1.14.542.1: #i29745# Support to access help content provider with string instead of an unsigned short<commit_after>/*************************************************************************
 *
 *  $RCSfile: sfxhelp.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-30 17:34:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SFX_HELP_HXX
#define _SFX_HELP_HXX

#ifndef _HELP_HXX //autogen
#include <vcl/help.hxx>
#endif

#include <tools/string.hxx>

class SfxHelp_Impl;
class SfxFrame;
class SfxHelp : public Help
{
    String          aTicket;        // for Plugins
    String          aUser;
    String          aLanguageStr;
    String          aCountryStr;
    sal_Bool        bIsDebug;
    SfxHelp_Impl*   pImp;

private:
    virtual BOOL    Start( ULONG nHelpId, const Window* pWindow );
    virtual BOOL    Start( const String& rURL, const Window* pWindow );

    String          GetHelpModuleName_Impl( ULONG nHelpId );
    String          CreateHelpURL_Impl( ULONG nHelpId, const String& rModuleName );
    String          CreateHelpURL_Impl( const String& aCommandURL, const String& rModuleName );

public:

                    SfxHelp();
                    ~SfxHelp();
    void            SetTicket( const String& rTicket )
                    { aTicket = rTicket;}
    void            SetUser( const String& rUser )
                    { aUser = rUser;}

    virtual XubString   GetHelpText( ULONG nHelpId, const Window* pWindow );
    virtual XubString   GetHelpText( const String&, const Window* pWindow );

    static String       CreateHelpURL( ULONG nHelpId, const String& rModuleName );
    static String       CreateHelpURL( const String& aCommandURL, const String& rModuleName );
    static void         OpenHelpAgent( SfxFrame* pFrame, ULONG nHelpId );
};

#endif // #ifndef _SFX_HELP_HXX

<|endoftext|>


<commit_before>/*
 * Copyright 2010-2019 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
 */

#include <bx/allocator.h>
#include <bx/filepath.h>
#include <bx/string.h>
#include <bx/readerwriter.h>
#include <bx/process.h>

#include "dialog.h"

#if BX_PLATFORM_WINDOWS
extern "C" void*    __stdcall GetModuleHandleA(const char* _moduleName);
extern "C" uint32_t __stdcall GetModuleFileNameA(void* _module, char* _outFilePath, uint32_t _size);

typedef uintptr_t (__stdcall *LPOFNHOOKPROC)(void*, uint32_t, uintptr_t, uint64_t);

struct OPENFILENAMEA
{
	uint32_t      structSize;
	void*         hwndOwner;
	void*         hinstance;
	const char*   filter;
	const char*   customFilter;
	uint32_t      maxCustomFilter;
	uint32_t      filterIndex;
	const char*   file;
	uint32_t      maxFile;
	const char*   fileTitle;
	uint32_t      maxFileTitle;
	const char*   initialDir;
	const char*   title;
	uint32_t      flags;
	uint16_t      fileOffset;
	uint16_t      fileExtension;
	const char*   defExt;
	uintptr_t     customData;
	LPOFNHOOKPROC hook;
	const char*   templateName;
	void*         reserved0;
	uint32_t      reserved1;
	uint32_t      flagsEx;
};

extern "C" bool __stdcall GetOpenFileNameA(OPENFILENAMEA* _ofn);

#endif // BX_PLATFORM_WINDOWS

class Split
{
public:
	Split(const bx::StringView& _str, char _ch)
	: m_str(_str)
	, m_token(_str.getPtr(), bx::strFind(_str, _ch).getPtr() )
	, m_ch(_ch)
	{
	}

	bx::StringView next()
	{
		bx::StringView result = m_token;
		m_token = bx::strTrim(
			  bx::StringView(m_token.getTerm()+1, bx::strFind(bx::StringView(m_token.getTerm()+1, m_str.getTerm() ), m_ch).getPtr() )
			, " \t\n"
			);
		return result;
	}

	bool isDone() const
	{
		return m_token.isEmpty();
	}

private:
	const bx::StringView& m_str;
	bx::StringView m_token;
	char m_ch;
};

#if !BX_PLATFORM_OSX
bool openFileSelectionDialog(
	  bx::FilePath& _inOutFilePath
	, FileSelectionDialogType::Enum _type
	, const bx::StringView& _title
	, const bx::StringView& _filter
	)
{
#if BX_PLATFORM_LINUX
	char tmp[4096];
	bx::StaticMemoryBlockWriter writer(tmp, sizeof(tmp) );

	bx::Error err;
	bx::write(&writer, &err
		, "--file-selection%s --title \"%.*s\" --filename \"%s\""
		, FileSelectionDialogType::Save == _type ? " --save" : ""
		, _title.getLength()
		, _title.getPtr()
		, _inOutFilePath.getCPtr()
		);

	for (bx::LineReader lr(_filter); !lr.isDone();)
	{
		const bx::StringView line = lr.next();

		bx::write(&writer, &err
			, " --file-filter \"%.*s\""
			, line.getLength()
			, line.getPtr()
			);
	}

	if (err.isOk() )
	{
		bx::ProcessReader pr;

		if (bx::open(&pr, "zenity", tmp, &err) )
		{
			char buffer[1024];
			int32_t total = bx::read(&pr, buffer, sizeof(buffer), &err);
			bx::close(&pr);

			if (0 == pr.getExitCode() )
			{
				_inOutFilePath.set(bx::strRTrim(bx::StringView(buffer, total), "\n\r") );
				return true;
			}
		}
	}
#elif BX_PLATFORM_WINDOWS
	BX_UNUSED(_type);

	char out[bx::kMaxFilePath] = { '\0' };

	OPENFILENAMEA ofn;
	bx::memSet(&ofn, 0, sizeof(ofn) );
	ofn.structSize = sizeof(OPENFILENAMEA);
	ofn.initialDir = _inOutFilePath.getCPtr();
	ofn.file       = out;
	ofn.maxFile    = sizeof(out);
	ofn.flags      = 0
		| /* OFN_EXPLORER        */ 0x00080000
		| /* OFN_FILEMUSTEXIST   */ 0x00001000
		| /* OFN_DONTADDTORECENT */ 0x02000000
		;

	char tmp[4096];
	bx::StaticMemoryBlockWriter writer(tmp, sizeof(tmp) );

	bx::Error err;

	ofn.title = tmp;
	bx::write(&writer, &err, "%.*s", _title.getLength(),  _title.getPtr() );
	bx::write(&writer, '\0', &err);

	ofn.filter = tmp + uint32_t(bx::seek(&writer) );

	for (bx::LineReader lr(_filter); !lr.isDone() && err.isOk();)
	{
		const bx::StringView line = lr.next();
		const bx::StringView sep  = bx::strFind(line, '|');

		if (!sep.isEmpty() )
		{
			bx::write(&writer, bx::strTrim(bx::StringView(line.getPtr(), sep.getPtr() ), " "), &err);
			bx::write(&writer, '\0', &err);

			bool first = true;

			for (Split split(bx::strTrim(bx::StringView(sep.getPtr()+1, line.getTerm() ), " "), ' '); !split.isDone() && err.isOk();)
			{
				const bx::StringView token = split.next();
				if (!first)
				{
					bx::write(&writer, ';', &err);
				}

				first = false;
				bx::write(&writer, token, &err);
			}

			bx::write(&writer, '\0', &err);
		}
		else
		{
			bx::write(&writer, line, &err);
			bx::write(&writer, '\0', &err);
			bx::write(&writer, '\0', &err);
		}
	}

	bx::write(&writer, '\0', &err);

	if (err.isOk()
	&&  GetOpenFileNameA(&ofn) )
	{
		_inOutFilePath.set(ofn.file);
		return true;
	}
#else
	BX_UNUSED(_inOutFilePath, _type, _title, _filter);
#endif // BX_PLATFORM_LINUX

	return false;
}
#endif // !BX_PLATFORM_OSX
<commit_msg>fix dialog null terminator (#1835)<commit_after>/*
 * Copyright 2010-2019 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
 */

#include <bx/allocator.h>
#include <bx/filepath.h>
#include <bx/string.h>
#include <bx/readerwriter.h>
#include <bx/process.h>

#include "dialog.h"

#if BX_PLATFORM_WINDOWS
extern "C" void*    __stdcall GetModuleHandleA(const char* _moduleName);
extern "C" uint32_t __stdcall GetModuleFileNameA(void* _module, char* _outFilePath, uint32_t _size);

typedef uintptr_t (__stdcall *LPOFNHOOKPROC)(void*, uint32_t, uintptr_t, uint64_t);

struct OPENFILENAMEA
{
	uint32_t      structSize;
	void*         hwndOwner;
	void*         hinstance;
	const char*   filter;
	const char*   customFilter;
	uint32_t      maxCustomFilter;
	uint32_t      filterIndex;
	const char*   file;
	uint32_t      maxFile;
	const char*   fileTitle;
	uint32_t      maxFileTitle;
	const char*   initialDir;
	const char*   title;
	uint32_t      flags;
	uint16_t      fileOffset;
	uint16_t      fileExtension;
	const char*   defExt;
	uintptr_t     customData;
	LPOFNHOOKPROC hook;
	const char*   templateName;
	void*         reserved0;
	uint32_t      reserved1;
	uint32_t      flagsEx;
};

extern "C" bool __stdcall GetOpenFileNameA(OPENFILENAMEA* _ofn);

#endif // BX_PLATFORM_WINDOWS

class Split
{
public:
	Split(const bx::StringView& _str, char _ch)
	: m_str(_str)
	, m_token(_str.getPtr(), bx::strFind(_str, _ch).getPtr() )
	, m_ch(_ch)
	{
	}

	bx::StringView next()
	{
		bx::StringView result = m_token;
		m_token = bx::strTrim(
			  bx::StringView(m_token.getTerm()+1, bx::strFind(bx::StringView(m_token.getTerm()+1, m_str.getTerm() ), m_ch).getPtr() )
			, " \t\n"
			);
		return result;
	}

	bool isDone() const
	{
		return m_token.isEmpty();
	}

private:
	const bx::StringView& m_str;
	bx::StringView m_token;
	char m_ch;
};

#if !BX_PLATFORM_OSX
bool openFileSelectionDialog(
	  bx::FilePath& _inOutFilePath
	, FileSelectionDialogType::Enum _type
	, const bx::StringView& _title
	, const bx::StringView& _filter
	)
{
#if BX_PLATFORM_LINUX
	char tmp[4096];
	bx::StaticMemoryBlockWriter writer(tmp, sizeof(tmp) );

	bx::Error err;
	bx::write(&writer, &err
		, "--file-selection%s --title \"%.*s\" --filename \"%s\""
		, FileSelectionDialogType::Save == _type ? " --save" : ""
		, _title.getLength()
		, _title.getPtr()
		, _inOutFilePath.getCPtr()
		);

	for (bx::LineReader lr(_filter); !lr.isDone();)
	{
		const bx::StringView line = lr.next();

		bx::write(&writer, &err
			, " --file-filter \"%.*s\""
			, line.getLength()
			, line.getPtr()
			);
	}

	bx::write(&writer, '\0', &err);

	if (err.isOk() )
	{
		bx::ProcessReader pr;

		if (bx::open(&pr, "zenity", tmp, &err) )
		{
			char buffer[1024];
			int32_t total = bx::read(&pr, buffer, sizeof(buffer), &err);
			bx::close(&pr);

			if (0 == pr.getExitCode() )
			{
				_inOutFilePath.set(bx::strRTrim(bx::StringView(buffer, total), "\n\r") );
				return true;
			}
		}
	}
#elif BX_PLATFORM_WINDOWS
	BX_UNUSED(_type);

	char out[bx::kMaxFilePath] = { '\0' };

	OPENFILENAMEA ofn;
	bx::memSet(&ofn, 0, sizeof(ofn) );
	ofn.structSize = sizeof(OPENFILENAMEA);
	ofn.initialDir = _inOutFilePath.getCPtr();
	ofn.file       = out;
	ofn.maxFile    = sizeof(out);
	ofn.flags      = 0
		| /* OFN_EXPLORER        */ 0x00080000
		| /* OFN_FILEMUSTEXIST   */ 0x00001000
		| /* OFN_DONTADDTORECENT */ 0x02000000
		;

	char tmp[4096];
	bx::StaticMemoryBlockWriter writer(tmp, sizeof(tmp) );

	bx::Error err;

	ofn.title = tmp;
	bx::write(&writer, &err, "%.*s", _title.getLength(),  _title.getPtr() );
	bx::write(&writer, '\0', &err);

	ofn.filter = tmp + uint32_t(bx::seek(&writer) );

	for (bx::LineReader lr(_filter); !lr.isDone() && err.isOk();)
	{
		const bx::StringView line = lr.next();
		const bx::StringView sep  = bx::strFind(line, '|');

		if (!sep.isEmpty() )
		{
			bx::write(&writer, bx::strTrim(bx::StringView(line.getPtr(), sep.getPtr() ), " "), &err);
			bx::write(&writer, '\0', &err);

			bool first = true;

			for (Split split(bx::strTrim(bx::StringView(sep.getPtr()+1, line.getTerm() ), " "), ' '); !split.isDone() && err.isOk();)
			{
				const bx::StringView token = split.next();
				if (!first)
				{
					bx::write(&writer, ';', &err);
				}

				first = false;
				bx::write(&writer, token, &err);
			}

			bx::write(&writer, '\0', &err);
		}
		else
		{
			bx::write(&writer, line, &err);
			bx::write(&writer, '\0', &err);
			bx::write(&writer, '\0', &err);
		}
	}

	bx::write(&writer, '\0', &err);

	if (err.isOk()
	&&  GetOpenFileNameA(&ofn) )
	{
		_inOutFilePath.set(ofn.file);
		return true;
	}
#else
	BX_UNUSED(_inOutFilePath, _type, _title, _filter);
#endif // BX_PLATFORM_LINUX

	return false;
}
#endif // !BX_PLATFORM_OSX
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "dumpvisitor.h"
#include <vespa/documentapi/messagebus/messages/multioperationmessage.h>
#include <vespa/document/update/documentupdate.h>
#include <vespa/vdslib/container/mutabledocumentlist.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/log/log.h>
LOG_SETUP(".visitor.instance.dumpvisitor");

namespace storage {

DumpVisitor::DumpVisitor(StorageComponent& component,
                         const vdslib::Parameters& params)
    : Visitor(component),
      _keepTimeStamps(false)
{
    if (params.hasValue("requestfields")) {
        std::string fields = params.get("requestfields");

        _requestedFields.reset(new std::set<std::string>());
        vespalib::StringTokenizer tokenizer(fields);
        for (uint32_t i = 0; i < tokenizer.size(); i++) {
            _requestedFields->insert(tokenizer[i]);
        }
    }

    if (params.hasValue("requestdocuments")) {
        std::string documents = params.get("requestdocuments");

        _requestedDocuments.reset(new std::set<std::string>());
        vespalib::StringTokenizer tokenizer(documents, " \t");
        for (uint32_t i = 0; i < tokenizer.size(); i++) {
            _requestedDocuments->insert(tokenizer[i]);
        }
    }

    if (params.hasValue("keeptimestamps")) {
	_keepTimeStamps = true;
    }

    LOG(debug, "Created DumpVisitor");
}

std::unique_ptr<documentapi::MultiOperationMessage>
DumpVisitor::createMultiOperation(const document::BucketId& bucketId,
                                  const std::vector<const document::Document*>& docs)
{
    for (int multiplier = 1; ; multiplier *= 2) {
        std::vector<char> buffer(getDocBlockSize() * multiplier);
        vdslib::MutableDocumentList newBlock(_component.getTypeRepo(),
                                             &buffer[0], buffer.size(), false);
        bool mustResizeBuffer = false;
        for (uint32_t i = 0; i < docs.size(); i++) {
            bool ok = newBlock.addPut(*docs[i], docs[i]->getLastModified());
            if (!ok) {
                mustResizeBuffer = true;
                break;
            }
        }

        if (!mustResizeBuffer) {
            return std::unique_ptr<documentapi::MultiOperationMessage>(
                    new documentapi::MultiOperationMessage(bucketId, newBlock, _keepTimeStamps));
        }
    }
    assert(false);
    return std::unique_ptr<documentapi::MultiOperationMessage>();
}

void DumpVisitor::handleDocuments(const document::BucketId& bucketId,
                                  std::vector<spi::DocEntry::LP>& entries,
                                  HitCounter& hitCounter)
{
    LOG(debug, "Visitor %s handling block of %zu documents.",
               _id.c_str(), entries.size());

    std::unique_ptr<documentapi::MultiOperationMessage> cmd;
    if (_requestedFields.get() || _requestedDocuments.get()) {
        std::vector<const document::Document*> newDocuments;

        // Remove all fields from the document that are not listed in
        // requestedFields.
        for (size_t i = 0; i < entries.size(); ++i) {
            std::unique_ptr<document::Document> d(entries[i]->getDocument()->clone());

            if (!_requestedDocuments.get()
                || _requestedDocuments->find(d->getId().toString())
                        != _requestedDocuments->end())
            {
                if (_requestedFields.get()) {
                    for (document::Document::const_iterator docIter
                            = d->begin(); docIter != d->end(); docIter++)
                    {
                        if (_requestedFields->find(docIter.field().getName())
                                == _requestedFields->end())
                        {
                            d->remove(docIter.field());
                        }
                    }
                }
                newDocuments.push_back(d.release());
            }
        }

        cmd = createMultiOperation(bucketId, newDocuments);

        // FIXME: not exception safe
        for (uint32_t i = 0; i < newDocuments.size(); i++) {
            delete newDocuments[i];
        }
    } else {
        std::vector<const document::Document*> docs;
        docs.reserve(entries.size());
        for (size_t i = 0; i < entries.size(); ++i) {
            docs.push_back(entries[i]->getDocument());
            assert(docs.back() != 0);
        }
        cmd = createMultiOperation(bucketId, docs);
    }

    for (vdslib::DocumentList::const_iterator iter
            = cmd->getOperations().begin();
         iter != cmd->getOperations().end(); iter++)
    {
        hitCounter.addHit(iter->getDocumentId(), iter->getSerializedSize());
    }

    sendMessage(documentapi::DocumentMessage::UP(cmd.release()));
}

}
<commit_msg>No more postfix operator.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "dumpvisitor.h"
#include <vespa/documentapi/messagebus/messages/multioperationmessage.h>
#include <vespa/document/update/documentupdate.h>
#include <vespa/vdslib/container/mutabledocumentlist.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/log/log.h>
LOG_SETUP(".visitor.instance.dumpvisitor");

namespace storage {

DumpVisitor::DumpVisitor(StorageComponent& component,
                         const vdslib::Parameters& params)
    : Visitor(component),
      _keepTimeStamps(false)
{
    if (params.hasValue("requestfields")) {
        std::string fields = params.get("requestfields");

        _requestedFields.reset(new std::set<std::string>());
        vespalib::StringTokenizer tokenizer(fields);
        for (uint32_t i = 0; i < tokenizer.size(); i++) {
            _requestedFields->insert(tokenizer[i]);
        }
    }

    if (params.hasValue("requestdocuments")) {
        std::string documents = params.get("requestdocuments");

        _requestedDocuments.reset(new std::set<std::string>());
        vespalib::StringTokenizer tokenizer(documents, " \t");
        for (uint32_t i = 0; i < tokenizer.size(); i++) {
            _requestedDocuments->insert(tokenizer[i]);
        }
    }

    if (params.hasValue("keeptimestamps")) {
	_keepTimeStamps = true;
    }

    LOG(debug, "Created DumpVisitor");
}

std::unique_ptr<documentapi::MultiOperationMessage>
DumpVisitor::createMultiOperation(const document::BucketId& bucketId,
                                  const std::vector<const document::Document*>& docs)
{
    for (int multiplier = 1; ; multiplier *= 2) {
        std::vector<char> buffer(getDocBlockSize() * multiplier);
        vdslib::MutableDocumentList newBlock(_component.getTypeRepo(),
                                             &buffer[0], buffer.size(), false);
        bool mustResizeBuffer = false;
        for (uint32_t i = 0; i < docs.size(); i++) {
            bool ok = newBlock.addPut(*docs[i], docs[i]->getLastModified());
            if (!ok) {
                mustResizeBuffer = true;
                break;
            }
        }

        if (!mustResizeBuffer) {
            return std::unique_ptr<documentapi::MultiOperationMessage>(
                    new documentapi::MultiOperationMessage(bucketId, newBlock, _keepTimeStamps));
        }
    }
    assert(false);
    return std::unique_ptr<documentapi::MultiOperationMessage>();
}

void DumpVisitor::handleDocuments(const document::BucketId& bucketId,
                                  std::vector<spi::DocEntry::LP>& entries,
                                  HitCounter& hitCounter)
{
    LOG(debug, "Visitor %s handling block of %zu documents.",
               _id.c_str(), entries.size());

    std::unique_ptr<documentapi::MultiOperationMessage> cmd;
    if (_requestedFields.get() || _requestedDocuments.get()) {
        std::vector<const document::Document*> newDocuments;

        // Remove all fields from the document that are not listed in
        // requestedFields.
        for (size_t i = 0; i < entries.size(); ++i) {
            std::unique_ptr<document::Document> d(entries[i]->getDocument()->clone());

            if (!_requestedDocuments.get()
                || _requestedDocuments->find(d->getId().toString())
                        != _requestedDocuments->end())
            {
                if (_requestedFields.get()) {
                    for (document::Document::const_iterator docIter
                            = d->begin(); docIter != d->end(); ++docIter)
                    {
                        if (_requestedFields->find(docIter.field().getName())
                                == _requestedFields->end())
                        {
                            d->remove(docIter.field());
                        }
                    }
                }
                newDocuments.push_back(d.release());
            }
        }

        cmd = createMultiOperation(bucketId, newDocuments);

        // FIXME: not exception safe
        for (uint32_t i = 0; i < newDocuments.size(); i++) {
            delete newDocuments[i];
        }
    } else {
        std::vector<const document::Document*> docs;
        docs.reserve(entries.size());
        for (size_t i = 0; i < entries.size(); ++i) {
            docs.push_back(entries[i]->getDocument());
            assert(docs.back() != 0);
        }
        cmd = createMultiOperation(bucketId, docs);
    }

    for (vdslib::DocumentList::const_iterator iter
            = cmd->getOperations().begin();
         iter != cmd->getOperations().end(); iter++)
    {
        hitCounter.addHit(iter->getDocumentId(), iter->getSerializedSize());
    }

    sendMessage(documentapi::DocumentMessage::UP(cmd.release()));
}

}
<|endoftext|>


<commit_before>#ifndef DELETE_DELETER_HPP
#define DELETE_DELETER_HPP

#include "../traits.hpp"

namespace kq::resource::cleanup
{

template<typename T, typename Resource>
struct delete_deleter
{
	using traits = traits::get_traits<T>;
	using type = typename traits::type;

	void clean(){
		using storage = typename Resource::storage;
		auto& full_type = static_cast<Resource&>(*this);
		delete full_type.storage::get();
		full_type.storage::nullify();
	}
};

} // kq::resource::cleanup

#endif // DELETE_DELETER_HPP
<commit_msg>added support for array deletion<commit_after>#ifndef DELETE_DELETER_HPP
#define DELETE_DELETER_HPP

#include "../traits.hpp"

namespace kq::resource::cleanup
{

namespace detail
{
template<bool IsArray = false>
struct delete_caller
{
	template<typename T>
	static void call(T* ptr){
		delete ptr;
	}
};

template<>
struct delete_caller<true>
{
	template<typename T>
	static void call(T* ptr){
		delete[] ptr;
	}
};
}

template<typename T, typename Resource>
struct delete_deleter
{
	using traits = traits::get_traits<T>;
	using type = typename traits::type;

	void clean(){
		using storage = typename Resource::storage;
		auto& full_type = static_cast<Resource&>(*this);
		detail::delete_caller<std::is_array<T>::value>::call(full_type.storage::get());
		full_type.storage::nullify();
	}
};

} // kq::resource::cleanup

#endif // DELETE_DELETER_HPP
<|endoftext|>