raw
genesis                 1 // Copyright (c) 2009-2010 Satoshi Nakamoto
genesis 2 // Copyright (c) 2009-2012 The Bitcoin developers
genesis 3 // Distributed under the MIT/X11 software license, see the accompanying
genesis 4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
genesis 5 #ifndef BITCOIN_UTIL_H
genesis 6 #define BITCOIN_UTIL_H
genesis 7
genesis 8 #include "uint256.h"
genesis 9
asciilifeform-kil... 10 #include <stdint.h>
genesis 11 #include <sys/types.h>
genesis 12 #include <sys/time.h>
genesis 13 #include <sys/resource.h>
genesis 14 #include <map>
genesis 15 #include <vector>
genesis 16 #include <string>
genesis 17
genesis 18 #include <boost/thread.hpp>
genesis 19 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
genesis 20 #include <boost/date_time/gregorian/gregorian_types.hpp>
genesis 21 #include <boost/date_time/posix_time/posix_time_types.hpp>
genesis 22
genesis 23 #include <openssl/sha.h>
genesis 24 #include <openssl/ripemd.h>
genesis 25
genesis 26
genesis 27 typedef long long int64;
genesis 28 typedef unsigned long long uint64;
bitcoin-asciilife... 29
genesis 30 #define __forceinline inline
genesis 31
genesis 32 #define loop for (;;)
genesis 33 #define BEGIN(a) ((char*)&(a))
genesis 34 #define END(a) ((char*)&((&(a))[1]))
genesis 35 #define UBEGIN(a) ((unsigned char*)&(a))
genesis 36 #define UEND(a) ((unsigned char*)&((&(a))[1]))
genesis 37 #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
genesis 38 #define printf OutputDebugStringF
genesis 39
genesis 40 #ifdef snprintf
genesis 41 #undef snprintf
genesis 42 #endif
genesis 43 #define snprintf my_snprintf
genesis 44
genesis 45 #ifndef PRI64d
genesis 46 #define PRI64d "lld"
genesis 47 #define PRI64u "llu"
genesis 48 #define PRI64x "llx"
genesis 49 #endif
genesis 50
genesis 51 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
genesis 52 #define PAIRTYPE(t1, t2) std::pair<t1, t2>
genesis 53
genesis 54 // Align by increasing pointer, must have extra space at end of buffer
genesis 55 template <size_t nBytes, typename T>
genesis 56 T* alignup(T* p)
genesis 57 {
genesis 58 union
genesis 59 {
genesis 60 T* ptr;
genesis 61 size_t n;
genesis 62 } u;
genesis 63 u.ptr = p;
genesis 64 u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
genesis 65 return u.ptr;
genesis 66 }
genesis 67
genesis 68 #define WSAGetLastError() errno
genesis 69 #define WSAEINVAL EINVAL
genesis 70 #define WSAEALREADY EALREADY
genesis 71 #define WSAEWOULDBLOCK EWOULDBLOCK
genesis 72 #define WSAEMSGSIZE EMSGSIZE
genesis 73 #define WSAEINTR EINTR
genesis 74 #define WSAEINPROGRESS EINPROGRESS
genesis 75 #define WSAEADDRINUSE EADDRINUSE
genesis 76 #define WSAENOTSOCK EBADF
genesis 77 #define INVALID_SOCKET (SOCKET)(~0)
genesis 78 #define SOCKET_ERROR -1
genesis 79 typedef u_int SOCKET;
genesis 80 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
genesis 81 #define strlwr(psz) to_lower(psz)
genesis 82 #define _strlwr(psz) to_lower(psz)
genesis 83 #define MAX_PATH 1024
genesis 84 #define Beep(n1,n2) (0)
genesis 85 inline void Sleep(int64 n)
genesis 86 {
genesis 87 /*Boost has a year 2038 problem- if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
genesis 88 So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
genesis 89 boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
genesis 90 }
bitcoin-asciilife... 91
genesis 92
genesis 93 inline int myclosesocket(SOCKET& hSocket)
genesis 94 {
genesis 95 if (hSocket == INVALID_SOCKET)
genesis 96 return WSAENOTSOCK;
genesis 97 int ret = close(hSocket);
genesis 98 hSocket = INVALID_SOCKET;
genesis 99 return ret;
genesis 100 }
genesis 101 #define closesocket(s) myclosesocket(s)
genesis 102 inline const char* _(const char* psz)
genesis 103 {
genesis 104 return psz;
genesis 105 }
bitcoin-asciilife... 106
genesis 107
genesis 108 extern std::map<std::string, std::string> mapArgs;
genesis 109 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
genesis 110 extern bool fDebug;
genesis 111 extern bool fPrintToConsole;
genesis 112 extern bool fPrintToDebugger;
asciilifeform_and... 113 extern bool fCanEat;
genesis 114 extern char pszSetDataDir[MAX_PATH];
genesis 115 extern bool fRequestShutdown;
genesis 116 extern bool fShutdown;
genesis 117 extern bool fDaemon;
genesis 118 extern bool fServer;
genesis 119 extern bool fCommandLine;
genesis 120 extern std::string strMiscWarning;
genesis 121 extern bool fTestNet;
genesis 122 extern bool fNoListen;
genesis 123 extern bool fLogTimestamps;
genesis 124
genesis 125 void RandAddSeed();
genesis 126 void RandAddSeedPerfmon();
genesis 127 int OutputDebugStringF(const char* pszFormat, ...);
genesis 128 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
genesis 129 std::string strprintf(const std::string &format, ...);
genesis 130 bool error(const std::string &format, ...);
genesis 131 void LogException(std::exception* pex, const char* pszThread);
genesis 132 void PrintException(std::exception* pex, const char* pszThread);
genesis 133 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
genesis 134 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
genesis 135 std::string FormatMoney(int64 n, bool fPlus=false);
genesis 136 bool ParseMoney(const std::string& str, int64& nRet);
genesis 137 bool ParseMoney(const char* pszIn, int64& nRet);
genesis 138 std::vector<unsigned char> ParseHex(const char* psz);
genesis 139 std::vector<unsigned char> ParseHex(const std::string& str);
genesis 140 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
genesis 141 std::string DecodeBase64(const std::string& str);
genesis 142 std::string EncodeBase64(const unsigned char* pch, size_t len);
genesis 143 std::string EncodeBase64(const std::string& str);
genesis 144 void ParseParameters(int argc, char* argv[]);
genesis 145 const char* wxGetTranslation(const char* psz);
genesis 146 bool WildcardMatch(const char* psz, const char* mask);
genesis 147 bool WildcardMatch(const std::string& str, const std::string& mask);
genesis 148 int GetFilesize(FILE* file);
genesis 149 void GetDataDir(char* pszDirRet);
genesis 150 std::string GetConfigFile();
genesis 151 std::string GetPidFile();
genesis 152 void CreatePidFile(std::string pidFile, pid_t pid);
genesis 153 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
genesis 154 std::string GetDefaultDataDir();
genesis 155 std::string GetDataDir();
genesis 156 void ShrinkDebugFile();
genesis 157 int GetRandInt(int nMax);
genesis 158 uint64 GetRand(uint64 nMax);
genesis 159 int64 GetTime();
genesis 160 void SetMockTime(int64 nMockTimeIn);
genesis 161 int64 GetAdjustedTime();
genesis 162 void AddTimeData(unsigned int ip, int64 nTime);
genesis 163 std::string FormatFullVersion();
genesis 164
genesis 165
genesis 166
genesis 167
genesis 168
genesis 169
genesis 170
genesis 171
genesis 172
genesis 173
genesis 174
genesis 175
genesis 176
genesis 177 // Wrapper to automatically initialize mutex
genesis 178 class CCriticalSection
genesis 179 {
genesis 180 protected:
genesis 181 boost::interprocess::interprocess_recursive_mutex mutex;
genesis 182 public:
genesis 183 explicit CCriticalSection() { }
genesis 184 ~CCriticalSection() { }
genesis 185 void Enter(const char* pszName, const char* pszFile, int nLine);
genesis 186 void Leave();
genesis 187 bool TryEnter(const char* pszName, const char* pszFile, int nLine);
genesis 188 };
genesis 189
genesis 190 // Automatically leave critical section when leaving block, needed for exception safety
genesis 191 class CCriticalBlock
genesis 192 {
genesis 193 protected:
genesis 194 CCriticalSection* pcs;
genesis 195
genesis 196 public:
genesis 197 CCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
genesis 198 {
genesis 199 pcs = &csIn;
genesis 200 pcs->Enter(pszName, pszFile, nLine);
genesis 201 }
genesis 202
genesis 203 operator bool() const
genesis 204 {
genesis 205 return true;
genesis 206 }
genesis 207
genesis 208 ~CCriticalBlock()
genesis 209 {
genesis 210 pcs->Leave();
genesis 211 }
genesis 212 };
genesis 213
genesis 214 #define CRITICAL_BLOCK(cs) \
genesis 215 if (CCriticalBlock criticalblock = CCriticalBlock(cs, #cs, __FILE__, __LINE__))
genesis 216
genesis 217 #define ENTER_CRITICAL_SECTION(cs) \
genesis 218 (cs).Enter(#cs, __FILE__, __LINE__)
genesis 219
genesis 220 #define LEAVE_CRITICAL_SECTION(cs) \
genesis 221 (cs).Leave()
genesis 222
genesis 223 class CTryCriticalBlock
genesis 224 {
genesis 225 protected:
genesis 226 CCriticalSection* pcs;
genesis 227
genesis 228 public:
genesis 229 CTryCriticalBlock(CCriticalSection& csIn, const char* pszName, const char* pszFile, int nLine)
genesis 230 {
genesis 231 pcs = (csIn.TryEnter(pszName, pszFile, nLine) ? &csIn : NULL);
genesis 232 }
genesis 233
genesis 234 operator bool() const
genesis 235 {
genesis 236 return Entered();
genesis 237 }
genesis 238
genesis 239 ~CTryCriticalBlock()
genesis 240 {
genesis 241 if (pcs)
genesis 242 {
genesis 243 pcs->Leave();
genesis 244 }
genesis 245 }
genesis 246 bool Entered() const { return pcs != NULL; }
genesis 247 };
genesis 248
genesis 249 #define TRY_CRITICAL_BLOCK(cs) \
genesis 250 if (CTryCriticalBlock criticalblock = CTryCriticalBlock(cs, #cs, __FILE__, __LINE__))
genesis 251
genesis 252
genesis 253
genesis 254
genesis 255
genesis 256
genesis 257 // This is exactly like std::string, but with a custom allocator.
genesis 258 // (secure_allocator<> is defined in serialize.h)
genesis 259 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
genesis 260
genesis 261 // This is exactly like std::string, but with a custom allocator.
genesis 262 // (secure_allocator<> is defined in serialize.h)
genesis 263 typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
genesis 264
genesis 265
genesis 266
genesis 267
genesis 268
genesis 269 inline std::string i64tostr(int64 n)
genesis 270 {
genesis 271 return strprintf("%"PRI64d, n);
genesis 272 }
genesis 273
genesis 274 inline std::string itostr(int n)
genesis 275 {
genesis 276 return strprintf("%d", n);
genesis 277 }
genesis 278
genesis 279 inline int64 atoi64(const char* psz)
genesis 280 {
genesis 281 return strtoll(psz, NULL, 10);
genesis 282 }
genesis 283
genesis 284 inline int64 atoi64(const std::string& str)
genesis 285 {
genesis 286 return strtoll(str.c_str(), NULL, 10);
genesis 287 }
genesis 288
genesis 289 inline int atoi(const std::string& str)
genesis 290 {
genesis 291 return atoi(str.c_str());
genesis 292 }
genesis 293
genesis 294 inline int roundint(double d)
genesis 295 {
genesis 296 return (int)(d > 0 ? d + 0.5 : d - 0.5);
genesis 297 }
genesis 298
genesis 299 inline int64 roundint64(double d)
genesis 300 {
genesis 301 return (int64)(d > 0 ? d + 0.5 : d - 0.5);
genesis 302 }
genesis 303
genesis 304 inline int64 abs64(int64 n)
genesis 305 {
genesis 306 return (n >= 0 ? n : -n);
genesis 307 }
genesis 308
genesis 309 template<typename T>
genesis 310 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
genesis 311 {
genesis 312 if (itbegin == itend)
genesis 313 return "";
genesis 314 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
genesis 315 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
genesis 316 std::string str;
genesis 317 str.reserve((pend-pbegin) * (fSpaces ? 3 : 2));
genesis 318 for (const unsigned char* p = pbegin; p != pend; p++)
genesis 319 str += strprintf((fSpaces && p != pend-1 ? "%02x " : "%02x"), *p);
genesis 320 return str;
genesis 321 }
genesis 322
genesis 323 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
genesis 324 {
genesis 325 return HexStr(vch.begin(), vch.end(), fSpaces);
genesis 326 }
genesis 327
genesis 328 template<typename T>
genesis 329 std::string HexNumStr(const T itbegin, const T itend, bool f0x=true)
genesis 330 {
genesis 331 if (itbegin == itend)
genesis 332 return "";
genesis 333 const unsigned char* pbegin = (const unsigned char*)&itbegin[0];
genesis 334 const unsigned char* pend = pbegin + (itend - itbegin) * sizeof(itbegin[0]);
genesis 335 std::string str = (f0x ? "0x" : "");
genesis 336 str.reserve(str.size() + (pend-pbegin) * 2);
genesis 337 for (const unsigned char* p = pend-1; p >= pbegin; p--)
genesis 338 str += strprintf("%02x", *p);
genesis 339 return str;
genesis 340 }
genesis 341
genesis 342 inline std::string HexNumStr(const std::vector<unsigned char>& vch, bool f0x=true)
genesis 343 {
genesis 344 return HexNumStr(vch.begin(), vch.end(), f0x);
genesis 345 }
genesis 346
genesis 347 template<typename T>
genesis 348 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
genesis 349 {
genesis 350 printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
genesis 351 }
genesis 352
genesis 353 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
genesis 354 {
genesis 355 printf(pszFormat, HexStr(vch, fSpaces).c_str());
genesis 356 }
genesis 357
genesis 358 inline int64 GetPerformanceCounter()
genesis 359 {
genesis 360 int64 nCounter = 0;
genesis 361 timeval t;
genesis 362 gettimeofday(&t, NULL);
genesis 363 nCounter = t.tv_sec * 1000000 + t.tv_usec;
genesis 364 return nCounter;
genesis 365 }
genesis 366
genesis 367 inline int64 GetTimeMillis()
genesis 368 {
genesis 369 return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
genesis 370 boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
genesis 371 }
genesis 372
genesis 373 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
genesis 374 {
genesis 375 time_t n = nTime;
genesis 376 struct tm* ptmTime = gmtime(&n);
genesis 377 char pszTime[200];
genesis 378 strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
genesis 379 return pszTime;
genesis 380 }
genesis 381
genesis 382 template<typename T>
genesis 383 void skipspaces(T& it)
genesis 384 {
genesis 385 while (isspace(*it))
genesis 386 ++it;
genesis 387 }
genesis 388
genesis 389 inline bool IsSwitchChar(char c)
genesis 390 {
genesis 391 return c == '-';
genesis 392 }
genesis 393
genesis 394 inline std::string GetArg(const std::string& strArg, const std::string& strDefault)
genesis 395 {
genesis 396 if (mapArgs.count(strArg))
genesis 397 return mapArgs[strArg];
genesis 398 return strDefault;
genesis 399 }
genesis 400
genesis 401 inline int64 GetArg(const std::string& strArg, int64 nDefault)
genesis 402 {
genesis 403 if (mapArgs.count(strArg))
genesis 404 return atoi64(mapArgs[strArg]);
genesis 405 return nDefault;
genesis 406 }
genesis 407
genesis 408 inline bool GetBoolArg(const std::string& strArg, bool fDefault=false)
genesis 409 {
genesis 410 if (mapArgs.count(strArg))
genesis 411 {
genesis 412 if (mapArgs[strArg].empty())
genesis 413 return true;
genesis 414 return (atoi(mapArgs[strArg]) != 0);
genesis 415 }
genesis 416 return fDefault;
genesis 417 }
genesis 418
genesis 419 /**
genesis 420 * Set an argument if it doesn't already have a value
genesis 421 *
genesis 422 * @param strArg Argument to set (e.g. "-foo")
genesis 423 * @param strValue Value (e.g. "1")
genesis 424 * @return true if argument gets set, false if it already had a value
genesis 425 */
genesis 426 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
genesis 427
genesis 428 /**
genesis 429 * Set a boolean argument if it doesn't already have a value
genesis 430 *
genesis 431 * @param strArg Argument to set (e.g. "-foo")
genesis 432 * @param fValue Value (e.g. false)
genesis 433 * @return true if argument gets set, false if it already had a value
genesis 434 */
genesis 435 bool SoftSetArg(const std::string& strArg, bool fValue);
genesis 436
genesis 437
genesis 438
genesis 439
genesis 440
genesis 441
genesis 442
genesis 443
genesis 444
genesis 445 inline void heapchk()
genesis 446 {
genesis 447 }
genesis 448
genesis 449 // Randomize the stack to help protect against buffer overrun exploits
genesis 450 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn) \
genesis 451 { \
genesis 452 static char nLoops; \
genesis 453 if (nLoops <= 0) \
genesis 454 nLoops = GetRand(20) + 1; \
genesis 455 if (nLoops-- > 1) \
genesis 456 { \
genesis 457 ThreadFn; \
genesis 458 return; \
genesis 459 } \
genesis 460 }
genesis 461
genesis 462 #define CATCH_PRINT_EXCEPTION(pszFn) \
genesis 463 catch (std::exception& e) { \
genesis 464 PrintException(&e, (pszFn)); \
genesis 465 } catch (...) { \
genesis 466 PrintException(NULL, (pszFn)); \
genesis 467 }
genesis 468
genesis 469
genesis 470
genesis 471
genesis 472
genesis 473
genesis 474
genesis 475
genesis 476
genesis 477
genesis 478 template<typename T1>
genesis 479 inline uint256 Hash(const T1 pbegin, const T1 pend)
genesis 480 {
genesis 481 static unsigned char pblank[1];
genesis 482 uint256 hash1;
genesis 483 SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
genesis 484 uint256 hash2;
genesis 485 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
genesis 486 return hash2;
genesis 487 }
genesis 488
genesis 489 template<typename T1, typename T2>
genesis 490 inline uint256 Hash(const T1 p1begin, const T1 p1end,
genesis 491 const T2 p2begin, const T2 p2end)
genesis 492 {
genesis 493 static unsigned char pblank[1];
genesis 494 uint256 hash1;
genesis 495 SHA256_CTX ctx;
genesis 496 SHA256_Init(&ctx);
genesis 497 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
genesis 498 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
genesis 499 SHA256_Final((unsigned char*)&hash1, &ctx);
genesis 500 uint256 hash2;
genesis 501 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
genesis 502 return hash2;
genesis 503 }
genesis 504
genesis 505 template<typename T1, typename T2, typename T3>
genesis 506 inline uint256 Hash(const T1 p1begin, const T1 p1end,
genesis 507 const T2 p2begin, const T2 p2end,
genesis 508 const T3 p3begin, const T3 p3end)
genesis 509 {
genesis 510 static unsigned char pblank[1];
genesis 511 uint256 hash1;
genesis 512 SHA256_CTX ctx;
genesis 513 SHA256_Init(&ctx);
genesis 514 SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
genesis 515 SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
genesis 516 SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
genesis 517 SHA256_Final((unsigned char*)&hash1, &ctx);
genesis 518 uint256 hash2;
genesis 519 SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
genesis 520 return hash2;
genesis 521 }
genesis 522
genesis 523 template<typename T>
genesis 524 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=VERSION)
genesis 525 {
genesis 526 // Most of the time is spent allocating and deallocating CDataStream's
genesis 527 // buffer. If this ever needs to be optimized further, make a CStaticStream
genesis 528 // class with its buffer on the stack.
genesis 529 CDataStream ss(nType, nVersion);
genesis 530 ss.reserve(10000);
genesis 531 ss << obj;
genesis 532 return Hash(ss.begin(), ss.end());
genesis 533 }
genesis 534
genesis 535 inline uint160 Hash160(const std::vector<unsigned char>& vch)
genesis 536 {
genesis 537 uint256 hash1;
genesis 538 SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
genesis 539 uint160 hash2;
genesis 540 RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
genesis 541 return hash2;
genesis 542 }
genesis 543
genesis 544
genesis 545 // Median filter over a stream of values
genesis 546 // Returns the median of the last N numbers
genesis 547 template <typename T> class CMedianFilter
genesis 548 {
genesis 549 private:
genesis 550 std::vector<T> vValues;
genesis 551 std::vector<T> vSorted;
genesis 552 int nSize;
genesis 553 public:
genesis 554 CMedianFilter(int size, T initial_value):
genesis 555 nSize(size)
genesis 556 {
genesis 557 vValues.reserve(size);
genesis 558 vValues.push_back(initial_value);
genesis 559 vSorted = vValues;
genesis 560 }
genesis 561
genesis 562 void input(T value)
genesis 563 {
genesis 564 if(vValues.size() == nSize)
genesis 565 {
genesis 566 vValues.erase(vValues.begin());
genesis 567 }
genesis 568 vValues.push_back(value);
genesis 569
genesis 570 vSorted.resize(vValues.size());
genesis 571 std::copy(vValues.begin(), vValues.end(), vSorted.begin());
genesis 572 std::sort(vSorted.begin(), vSorted.end());
genesis 573 }
genesis 574
genesis 575 T median() const
genesis 576 {
genesis 577 int size = vSorted.size();
genesis 578 assert(size>0);
genesis 579 if(size & 1) // Odd number of elements
genesis 580 {
genesis 581 return vSorted[size/2];
genesis 582 }
genesis 583 else // Even number of elements
genesis 584 {
genesis 585 return (vSorted[size/2-1] + vSorted[size/2]) / 2;
genesis 586 }
genesis 587 }
genesis 588 };
genesis 589
genesis 590
genesis 591
genesis 592
genesis 593
genesis 594
genesis 595
genesis 596
genesis 597
genesis 598
genesis 599 // Note: It turns out we might have been able to use boost::thread
genesis 600 // by using TerminateThread(boost::thread.native_handle(), 0);
genesis 601 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
genesis 602 {
genesis 603 pthread_t hthread = 0;
genesis 604 int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
genesis 605 if (ret != 0)
genesis 606 {
genesis 607 printf("Error: pthread_create() returned %d\n", ret);
genesis 608 return (pthread_t)0;
genesis 609 }
genesis 610 if (!fWantHandle)
genesis 611 {
genesis 612 pthread_detach(hthread);
genesis 613 return (pthread_t)-1;
genesis 614 }
genesis 615 return hthread;
genesis 616 }
genesis 617
genesis 618 #define THREAD_PRIORITY_LOWEST PRIO_MAX
genesis 619 #define THREAD_PRIORITY_BELOW_NORMAL 2
genesis 620 #define THREAD_PRIORITY_NORMAL 0
genesis 621 #define THREAD_PRIORITY_ABOVE_NORMAL 0
genesis 622
genesis 623 inline void SetThreadPriority(int nPriority)
genesis 624 {
genesis 625 // It's unclear if it's even possible to change thread priorities on Linux,
genesis 626 // but we really and truly need it for the generation threads.
genesis 627 #ifdef PRIO_THREAD
genesis 628 setpriority(PRIO_THREAD, 0, nPriority);
genesis 629 #else
genesis 630 setpriority(PRIO_PROCESS, 0, nPriority);
genesis 631 #endif
genesis 632 }
genesis 633
genesis 634 inline bool TerminateThread(pthread_t hthread, unsigned int nExitCode)
genesis 635 {
genesis 636 return (pthread_cancel(hthread) == 0);
genesis 637 }
genesis 638
genesis 639 inline void ExitThread(size_t nExitCode)
genesis 640 {
genesis 641 pthread_exit((void*)nExitCode);
genesis 642 }
genesis 643
genesis 644
genesis 645
genesis 646 inline bool AffinityBugWorkaround(void(*pfn)(void*))
genesis 647 {
genesis 648 return false;
genesis 649 }
genesis 650
genesis 651 inline uint32_t ByteReverse(uint32_t value)
genesis 652 {
genesis 653 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
genesis 654 return (value<<16) | (value>>16);
genesis 655 }
genesis 656
genesis 657 #endif