Global.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. #pragma once
  2. /*
  3. * Global.h, part of VCMI engine
  4. *
  5. * Authors: listed in file AUTHORS in main folder
  6. *
  7. * License: GNU General Public License v2.0 or later
  8. * Full text of license available in license.txt file, in main folder
  9. *
  10. */
  11. /* ---------------------------------------------------------------------------- */
  12. /* Compiler detection */
  13. /* ---------------------------------------------------------------------------- */
  14. // Fixed width bool data type is important for serialization
  15. static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size.");
  16. #if defined _M_X64 && defined _WIN32 //Win64 -> cannot load 32-bit DLLs for video handling
  17. # define DISABLE_VIDEO
  18. #endif
  19. #ifdef __GNUC__
  20. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__)
  21. #endif
  22. #if !defined(__clang__) && defined(__GNUC__) && (GCC_VERSION < 470)
  23. # error VCMI requires at least gcc-4.7.2 for successful compilation or clang-3.1. Please update your compiler
  24. #endif
  25. #if defined(__GNUC__) && (GCC_VERSION == 470 || GCC_VERSION == 471)
  26. # error This GCC version has buggy std::array::at version and should not be used. Please update to 4.7.2 or later
  27. #endif
  28. /* ---------------------------------------------------------------------------- */
  29. /* Guarantee compiler features */
  30. /* ---------------------------------------------------------------------------- */
  31. //defining available c++11 features
  32. //initialization lists - gcc or clang
  33. #if defined(__clang__) || defined(__GNUC__)
  34. # define CPP11_USE_INITIALIZERS_LIST
  35. #endif
  36. /* ---------------------------------------------------------------------------- */
  37. /* Suppress some compiler warnings */
  38. /* ---------------------------------------------------------------------------- */
  39. #ifdef _MSC_VER
  40. # pragma warning (disable : 4800 ) /* disable conversion to bool warning -- I think it's intended in all places */
  41. #endif
  42. /* ---------------------------------------------------------------------------- */
  43. /* System detection. */
  44. /* ---------------------------------------------------------------------------- */
  45. // Based on: http://sourceforge.net/p/predef/wiki/OperatingSystems/
  46. // and on: http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
  47. // TODO?: Should be moved to vstd\os_detect.h (and then included by Global.h)
  48. #ifdef _WIN16 // Defined for 16-bit environments
  49. # error "16-bit Windows isn't supported"
  50. #elif defined(_WIN64) // Defined for 64-bit environments
  51. # define VCMI_WINDOWS
  52. # define VCMI_WINDOWS_64
  53. #elif defined(_WIN32) // Defined for both 32-bit and 64-bit environments
  54. # define VCMI_WINDOWS
  55. # define VCMI_WINDOWS_32
  56. #elif defined(_WIN32_WCE)
  57. # error "Windows CE isn't supported"
  58. #elif defined(__linux__) || defined(__gnu_linux__) || defined(linux) || defined(__linux)
  59. # define VCMI_UNIX
  60. # define VCMI_LINUX
  61. # ifdef __ANDROID__
  62. # define VCMI_ANDROID
  63. # endif
  64. #elif defined(__APPLE__) && defined(__MACH__)
  65. # define VCMI_UNIX
  66. # define VCMI_APPLE
  67. # include "TargetConditionals.h"
  68. # if TARGET_IPHONE_SIMULATOR
  69. # define VCMI_IOS
  70. # define VCMI_IOS_SIM
  71. # elif TARGET_OS_IPHONE
  72. # define VCMI_IOS
  73. # elif TARGET_OS_MAC
  74. # define VCMI_MAC
  75. # else
  76. //# warning "Unknown Apple target."?
  77. # endif
  78. #else
  79. # error "VCMI supports only Windows, OSX, Linux and Android targets"
  80. #endif
  81. #ifdef VCMI_IOS
  82. # error "iOS system isn't yet supported."
  83. #endif
  84. /* ---------------------------------------------------------------------------- */
  85. /* Commonly used C++, Boost headers */
  86. /* ---------------------------------------------------------------------------- */
  87. #ifdef VCMI_WINDOWS
  88. # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - delete this line if something is missing.
  89. # define NOMINMAX // Exclude min/max macros from <Windows.h>. Use std::[min/max] from <algorithm> instead.
  90. #endif
  91. #define _USE_MATH_DEFINES
  92. #include <cstdio>
  93. #include <stdio.h>
  94. #include <algorithm>
  95. #include <array>
  96. #include <cassert>
  97. #include <climits>
  98. #include <cmath>
  99. #include <cstdlib>
  100. #include <functional>
  101. #include <fstream>
  102. #include <iomanip>
  103. #include <iostream>
  104. #include <map>
  105. #include <memory>
  106. #include <numeric>
  107. #include <queue>
  108. #include <random>
  109. #include <set>
  110. #include <sstream>
  111. #include <string>
  112. #include <unordered_set>
  113. #include <unordered_map>
  114. #include <utility>
  115. #include <vector>
  116. //The only available version is 3, as of Boost 1.50
  117. #include <boost/version.hpp>
  118. #define BOOST_FILESYSTEM_VERSION 3
  119. #if BOOST_VERSION > 105000
  120. # define BOOST_THREAD_VERSION 3
  121. #endif
  122. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  123. #define BOOST_BIND_NO_PLACEHOLDERS
  124. #include <boost/algorithm/string.hpp>
  125. #include <boost/assign.hpp>
  126. #include <boost/cstdint.hpp>
  127. #include <boost/current_function.hpp>
  128. #include <boost/crc.hpp>
  129. #include <boost/date_time/posix_time/posix_time.hpp>
  130. #include <boost/date_time/posix_time/posix_time_io.hpp>
  131. #include <boost/filesystem.hpp>
  132. #include <boost/filesystem/path.hpp>
  133. #include <boost/filesystem/fstream.hpp>
  134. #include <boost/format.hpp>
  135. #include <boost/functional/hash.hpp>
  136. #include <boost/lexical_cast.hpp>
  137. #include <boost/locale/generator.hpp>
  138. #include <boost/logic/tribool.hpp>
  139. #include <boost/optional.hpp>
  140. #include <boost/program_options.hpp>
  141. #include <boost/range/adaptor/filtered.hpp>
  142. #include <boost/range/adaptor/reversed.hpp>
  143. #include <boost/range/algorithm.hpp>
  144. #include <boost/thread.hpp>
  145. #include <boost/variant.hpp>
  146. #include <boost/math/special_functions/round.hpp>
  147. #ifndef M_PI
  148. # define M_PI 3.14159265358979323846
  149. #endif
  150. /* ---------------------------------------------------------------------------- */
  151. /* Usings */
  152. /* ---------------------------------------------------------------------------- */
  153. using std::shared_ptr;
  154. using std::unique_ptr;
  155. using std::make_shared;
  156. using namespace std::placeholders;
  157. namespace range = boost::range;
  158. /* ---------------------------------------------------------------------------- */
  159. /* Typedefs */
  160. /* ---------------------------------------------------------------------------- */
  161. // Integral data types
  162. typedef boost::uint64_t ui64; //unsigned int 64 bits (8 bytes)
  163. typedef boost::uint32_t ui32; //unsigned int 32 bits (4 bytes)
  164. typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
  165. typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
  166. typedef boost::int64_t si64; //signed int 64 bits (8 bytes)
  167. typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
  168. typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
  169. typedef boost::int8_t si8; //signed int 8 bits (1 byte)
  170. // Lock typedefs
  171. typedef boost::lock_guard<boost::mutex> TLockGuard;
  172. typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
  173. /* ---------------------------------------------------------------------------- */
  174. /* Macros */
  175. /* ---------------------------------------------------------------------------- */
  176. // Import + Export macro declarations
  177. #ifdef VCMI_WINDOWS
  178. # ifdef __GNUC__
  179. # define DLL_IMPORT __attribute__((dllimport))
  180. # define DLL_EXPORT __attribute__((dllexport))
  181. # else
  182. # define DLL_IMPORT __declspec(dllimport)
  183. # define DLL_EXPORT __declspec(dllexport)
  184. # endif
  185. # define ELF_VISIBILITY
  186. #else
  187. # ifdef __GNUC__
  188. # define DLL_IMPORT __attribute__ ((visibility("default")))
  189. # define DLL_EXPORT __attribute__ ((visibility("default")))
  190. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  191. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  192. # endif
  193. #endif
  194. #ifdef VCMI_DLL
  195. # define DLL_LINKAGE DLL_EXPORT
  196. #else
  197. # define DLL_LINKAGE DLL_IMPORT
  198. #endif
  199. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  200. #define ASSERT_IF_CALLED_WITH_PLAYER if(!player) {logGlobal->errorStream() << BOOST_CURRENT_FUNCTION; assert(0);}
  201. //XXX pls dont - 'debug macros' are usually more trouble than it's worth
  202. #define HANDLE_EXCEPTION \
  203. catch (const std::exception& e) { \
  204. logGlobal->errorStream() << e.what(); \
  205. throw; \
  206. } \
  207. catch (const std::exception * e) \
  208. { \
  209. logGlobal->errorStream() << e->what(); \
  210. throw; \
  211. } \
  212. catch (const std::string& e) { \
  213. logGlobal->errorStream() << e; \
  214. throw; \
  215. }
  216. #define HANDLE_EXCEPTIONC(COMMAND) \
  217. catch (const std::exception& e) { \
  218. COMMAND; \
  219. logGlobal->errorStream() << e.what(); \
  220. throw; \
  221. } \
  222. catch (const std::string &e) \
  223. { \
  224. COMMAND; \
  225. logGlobal->errorStream() << e; \
  226. throw; \
  227. }
  228. // can be used for counting arrays
  229. template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
  230. #define ARRAY_COUNT(arr) (sizeof(_ArrayCountObj(arr)))
  231. // should be used for variables that becomes unused in release builds (e.g. only used for assert checks)
  232. #define UNUSED(VAR) ((void)VAR)
  233. /* ---------------------------------------------------------------------------- */
  234. /* VCMI standard library */
  235. /* ---------------------------------------------------------------------------- */
  236. #include "lib/logging/CLogger.h"
  237. void inline handleException()
  238. {
  239. try
  240. {
  241. throw;
  242. }
  243. catch(const std::exception & ex)
  244. {
  245. logGlobal->errorStream() << ex.what();
  246. }
  247. catch(const std::string & ex)
  248. {
  249. logGlobal->errorStream() << ex;
  250. }
  251. catch(...)
  252. {
  253. logGlobal->errorStream() << "Sorry, caught unknown exception type. No more info available.";
  254. }
  255. }
  256. template<typename T>
  257. std::ostream & operator<<(std::ostream & out, const boost::optional<T> & opt)
  258. {
  259. if(opt) return out << *opt;
  260. else return out << "empty";
  261. }
  262. template<typename T>
  263. std::ostream & operator<<(std::ostream & out, const std::vector<T> & container)
  264. {
  265. out << "[";
  266. for(auto it = container.begin(); it != container.end(); ++it)
  267. {
  268. out << *it;
  269. if(std::prev(container.end()) != it) out << ", ";
  270. }
  271. return out << "]";
  272. }
  273. namespace vstd
  274. {
  275. // combine hashes. Present in boost but not in std
  276. template <class T>
  277. inline void hash_combine(std::size_t& seed, const T& v)
  278. {
  279. std::hash<T> hasher;
  280. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  281. }
  282. //returns true if container c contains item i
  283. template <typename Container, typename Item>
  284. bool contains(const Container & c, const Item &i)
  285. {
  286. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  287. }
  288. //returns true if container c contains item i
  289. template <typename Container, typename Pred>
  290. bool contains_if(const Container & c, Pred p)
  291. {
  292. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  293. }
  294. //returns true if map c contains item i
  295. template <typename V, typename Item, typename Item2>
  296. bool contains(const std::map<Item,V> & c, const Item2 &i)
  297. {
  298. return c.find(i)!=c.end();
  299. }
  300. //returns true if unordered set c contains item i
  301. template <typename Item>
  302. bool contains(const std::unordered_set<Item> & c, const Item &i)
  303. {
  304. return c.find(i)!=c.end();
  305. }
  306. template <typename V, typename Item, typename Item2>
  307. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  308. {
  309. return c.find(i)!=c.end();
  310. }
  311. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  312. template <typename Container, typename T2>
  313. int find_pos(const Container & c, const T2 &s)
  314. {
  315. size_t i=0;
  316. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  317. if(*iter == s)
  318. return i;
  319. return -1;
  320. }
  321. //Func f tells if element matches
  322. template <typename Container, typename Func>
  323. int find_pos_if(const Container & c, const Func &f)
  324. {
  325. auto ret = boost::range::find_if(c, f);
  326. if(ret != std::end(c))
  327. return std::distance(std::begin(c), ret);
  328. return -1;
  329. }
  330. //returns iterator to the given element if present in container, end() if not
  331. template <typename Container, typename Item>
  332. typename Container::iterator find(Container & c, const Item &i)
  333. {
  334. return std::find(c.begin(),c.end(),i);
  335. }
  336. //returns const iterator to the given element if present in container, end() if not
  337. template <typename Container, typename Item>
  338. typename Container::const_iterator find(const Container & c, const Item &i)
  339. {
  340. return std::find(c.begin(),c.end(),i);
  341. }
  342. //removes element i from container c, returns false if c does not contain i
  343. template <typename Container, typename Item>
  344. typename Container::size_type operator-=(Container &c, const Item &i)
  345. {
  346. typename Container::iterator itr = find(c,i);
  347. if(itr == c.end())
  348. return false;
  349. c.erase(itr);
  350. return true;
  351. }
  352. //assigns greater of (a, b) to a and returns maximum of (a, b)
  353. template <typename t1, typename t2>
  354. t1 &amax(t1 &a, const t2 &b)
  355. {
  356. if(a >= b)
  357. return a;
  358. else
  359. {
  360. a = b;
  361. return a;
  362. }
  363. }
  364. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  365. template <typename t1, typename t2>
  366. t1 &amin(t1 &a, const t2 &b)
  367. {
  368. if(a <= b)
  369. return a;
  370. else
  371. {
  372. a = b;
  373. return a;
  374. }
  375. }
  376. //makes a to fit the range <b, c>
  377. template <typename t1, typename t2, typename t3>
  378. t1 &abetween(t1 &a, const t2 &b, const t3 &c)
  379. {
  380. amax(a,b);
  381. amin(a,c);
  382. return a;
  383. }
  384. //checks if a is between b and c
  385. template <typename t1, typename t2, typename t3>
  386. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  387. {
  388. return value > min && value < max;
  389. }
  390. //checks if a is within b and c
  391. template <typename t1, typename t2, typename t3>
  392. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  393. {
  394. return value >= min && value <= max;
  395. }
  396. template <typename t1, typename t2>
  397. struct assigner
  398. {
  399. public:
  400. t1 &op1;
  401. t2 op2;
  402. assigner(t1 &a1, const t2 & a2)
  403. :op1(a1), op2(a2)
  404. {}
  405. void operator()()
  406. {
  407. op1 = op2;
  408. }
  409. };
  410. // Assigns value a2 to a1. The point of time of the real operation can be controlled
  411. // with the () operator.
  412. template <typename t1, typename t2>
  413. assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
  414. {
  415. return assigner<t1,t2>(a1,a2);
  416. }
  417. //deleted pointer and sets it to nullptr
  418. template <typename T>
  419. void clear_pointer(T* &ptr)
  420. {
  421. delete ptr;
  422. ptr = nullptr;
  423. }
  424. #if _MSC_VER >= 1800
  425. using std::make_unique;
  426. #else
  427. template<typename T>
  428. std::unique_ptr<T> make_unique()
  429. {
  430. return std::unique_ptr<T>(new T());
  431. }
  432. template<typename T, typename Arg1>
  433. std::unique_ptr<T> make_unique(Arg1 &&arg1)
  434. {
  435. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
  436. }
  437. template<typename T, typename Arg1, typename Arg2>
  438. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
  439. {
  440. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
  441. }
  442. template<typename T, typename Arg1, typename Arg2, typename Arg3>
  443. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
  444. {
  445. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
  446. }
  447. template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  448. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
  449. {
  450. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
  451. }
  452. #endif
  453. template <typename Container>
  454. typename Container::const_reference circularAt(const Container &r, size_t index)
  455. {
  456. assert(r.size());
  457. index %= r.size();
  458. auto itr = std::begin(r);
  459. std::advance(itr, index);
  460. return *itr;
  461. }
  462. template<typename Range, typename Predicate>
  463. void erase_if(Range &vec, Predicate pred)
  464. {
  465. vec.erase(boost::remove_if(vec, pred),vec.end());
  466. }
  467. template<typename Elem, typename Predicate>
  468. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  469. {
  470. auto itr = setContainer.begin();
  471. auto endItr = setContainer.end();
  472. while(itr != endItr)
  473. {
  474. auto tmpItr = itr++;
  475. if(pred(*tmpItr))
  476. setContainer.erase(tmpItr);
  477. }
  478. }
  479. //works for map and std::map, maybe something else
  480. template<typename Key, typename Val, typename Predicate>
  481. void erase_if(std::map<Key, Val> &container, Predicate pred)
  482. {
  483. auto itr = container.begin();
  484. auto endItr = container.end();
  485. while(itr != endItr)
  486. {
  487. auto tmpItr = itr++;
  488. if(pred(*tmpItr))
  489. container.erase(tmpItr);
  490. }
  491. }
  492. template<typename InputRange, typename OutputIterator, typename Predicate>
  493. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  494. {
  495. return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
  496. }
  497. template <typename Container>
  498. std::insert_iterator<Container> set_inserter(Container &c)
  499. {
  500. return std::inserter(c, c.end());
  501. }
  502. //Returns iterator to the element for which the value of ValueFunction is minimal
  503. template<class ForwardRange, class ValueFunction>
  504. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  505. {
  506. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  507. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  508. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  509. * directly for both function parameters.
  510. */
  511. return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  512. {
  513. return vf(lhs) < vf(rhs);
  514. });
  515. }
  516. //Returns iterator to the element for which the value of ValueFunction is maximal
  517. template<class ForwardRange, class ValueFunction>
  518. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  519. {
  520. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  521. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  522. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  523. * directly for both function parameters.
  524. */
  525. return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  526. {
  527. return vf(lhs) < vf(rhs);
  528. });
  529. }
  530. template<typename T>
  531. void advance(T &obj, int change)
  532. {
  533. obj = (T)(((int)obj) + change);
  534. }
  535. template <typename Container>
  536. typename Container::value_type backOrNull(const Container &c) //returns last element of container or nullptr if it is empty (to be used with containers of pointers)
  537. {
  538. if(c.size())
  539. return c.back();
  540. else
  541. return typename Container::value_type();
  542. }
  543. template <typename Container>
  544. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or nullptr if it is empty (to be used with containers of pointers)
  545. {
  546. if(c.size())
  547. return c.front();
  548. else
  549. return nullptr;
  550. }
  551. template <typename Container, typename Index>
  552. bool isValidIndex(const Container &c, Index i)
  553. {
  554. return i >= 0 && i < c.size();
  555. }
  556. template <typename Container, typename Index>
  557. boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i)
  558. {
  559. if(isValidIndex(c, i))
  560. {
  561. auto itr = c.begin();
  562. std::advance(itr, i);
  563. return *itr;
  564. }
  565. return boost::none;
  566. }
  567. template <typename Container, typename Pred>
  568. static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t)
  569. {
  570. auto pos = range::find_if(r, t);
  571. if(pos == boost::end(r))
  572. return boost::none;
  573. else
  574. return *pos;
  575. }
  576. template <typename Container>
  577. typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
  578. {
  579. if(index < r.size())
  580. return r[index];
  581. return defaultValue;
  582. }
  583. template <typename Container, typename Item>
  584. bool erase_if_present(Container &c, const Item &item)
  585. {
  586. auto i = std::find(c.begin(), c.end(), item);
  587. if (i != c.end())
  588. {
  589. c.erase(i);
  590. return true;
  591. }
  592. return false;
  593. }
  594. template <typename V, typename Item, typename Item2>
  595. bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
  596. {
  597. auto i = c.find(item);
  598. if (i != c.end())
  599. {
  600. c.erase(i);
  601. return true;
  602. }
  603. return false;
  604. }
  605. template <typename Container, typename Pred>
  606. void erase(Container &c, Pred pred)
  607. {
  608. c.erase(boost::remove_if(c, pred), c.end());
  609. }
  610. template<typename T>
  611. void removeDuplicates(std::vector<T> &vec)
  612. {
  613. boost::sort(vec);
  614. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  615. }
  616. using boost::math::round;
  617. }
  618. using vstd::operator-=;
  619. using vstd::make_unique;