Update to 0.3.0 (New upstream + new RPC calls)
[novacoin.git] / src / util.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_UTIL_H
7 #define BITCOIN_UTIL_H
8
9 #include "uint256.h"
10
11 #ifndef WIN32
12 #include <sys/types.h>
13 #include <sys/time.h>
14 #include <sys/resource.h>
15 #else
16 typedef int pid_t; /* define for windows compatiblity */
17 #endif
18 #include <map>
19 #include <vector>
20 #include <string>
21
22 #include <boost/thread.hpp>
23 #include <boost/filesystem.hpp>
24 #include <boost/filesystem/path.hpp>
25 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
26 #include <boost/interprocess/sync/scoped_lock.hpp>
27 #include <boost/interprocess/sync/interprocess_semaphore.hpp>
28 #include <boost/interprocess/sync/lock_options.hpp>
29 #include <boost/date_time/gregorian/gregorian_types.hpp>
30 #include <boost/date_time/posix_time/posix_time_types.hpp>
31
32 #include <openssl/sha.h>
33 #include <openssl/ripemd.h>
34
35 #include "netbase.h" // for AddTimeData
36
37 typedef long long  int64;
38 typedef unsigned long long  uint64;
39
40 static const int64 COIN = 1000000;
41 static const int64 CENT = 10000;
42
43 #define loop                for (;;)
44 #define BEGIN(a)            ((char*)&(a))
45 #define END(a)              ((char*)&((&(a))[1]))
46 #define UBEGIN(a)           ((unsigned char*)&(a))
47 #define UEND(a)             ((unsigned char*)&((&(a))[1]))
48 #define ARRAYLEN(array)     (sizeof(array)/sizeof((array)[0]))
49 #define printf              OutputDebugStringF
50
51 #define UVOIDBEGIN(a)        ((void*)&(a))
52 #define CVOIDBEGIN(a)        ((const void*)&(a))
53 #define UINTBEGIN(a)        ((uint32_t*)&(a))
54 #define CUINTBEGIN(a)        ((const uint32_t*)&(a))
55
56 #ifdef snprintf
57 #undef snprintf
58 #endif
59 #define snprintf my_snprintf
60
61 #ifndef PRI64d
62 #if defined(_MSC_VER) || defined(__MSVCRT__)
63 #define PRI64d  "I64d"
64 #define PRI64u  "I64u"
65 #define PRI64x  "I64x"
66 #else
67 #define PRI64d  "lld"
68 #define PRI64u  "llu"
69 #define PRI64x  "llx"
70 #endif
71 #endif
72
73 // This is needed because the foreach macro can't get over the comma in pair<t1, t2>
74 #define PAIRTYPE(t1, t2)    std::pair<t1, t2>
75
76 // Align by increasing pointer, must have extra space at end of buffer
77 template <size_t nBytes, typename T>
78 T* alignup(T* p)
79 {
80     union
81     {
82         T* ptr;
83         size_t n;
84     } u;
85     u.ptr = p;
86     u.n = (u.n + (nBytes-1)) & ~(nBytes-1);
87     return u.ptr;
88 }
89
90 #ifdef WIN32
91 #define MSG_NOSIGNAL        0
92 #define MSG_DONTWAIT        0
93
94 #ifndef S_IRUSR
95 #define S_IRUSR             0400
96 #define S_IWUSR             0200
97 #endif
98 #define unlink              _unlink
99 #else
100 #define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
101 #define strlwr(psz)         to_lower(psz)
102 #define _strlwr(psz)        to_lower(psz)
103 #define MAX_PATH            1024
104 inline void Sleep(int64 n)
105 {
106     /*Boost has a year 2038 problem— if the request sleep time is past epoch+2^31 seconds the sleep returns instantly.
107       So we clamp our sleeps here to 10 years and hope that boost is fixed by 2028.*/
108     boost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(n>315576000000LL?315576000000LL:n));
109 }
110 #endif
111
112 #ifndef THROW_WITH_STACKTRACE
113 #define THROW_WITH_STACKTRACE(exception)  \
114 {                                         \
115     LogStackTrace();                      \
116     throw (exception);                    \
117 }
118 void LogStackTrace();
119 #endif
120
121
122
123
124
125
126 extern std::map<std::string, std::string> mapArgs;
127 extern std::map<std::string, std::vector<std::string> > mapMultiArgs;
128 extern bool fDebug;
129 extern bool fPrintToConsole;
130 extern bool fPrintToDebugger;
131 extern bool fRequestShutdown;
132 extern bool fShutdown;
133 extern bool fDaemon;
134 extern bool fServer;
135 extern bool fCommandLine;
136 extern std::string strMiscWarning;
137 extern bool fTestNet;
138 extern bool fNoListen;
139 extern bool fLogTimestamps;
140
141 void RandAddSeed();
142 void RandAddSeedPerfmon();
143 int OutputDebugStringF(const char* pszFormat, ...);
144 int my_snprintf(char* buffer, size_t limit, const char* format, ...);
145
146 /* It is not allowed to use va_start with a pass-by-reference argument.
147    (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
148    macro to keep similar semantics.
149 */
150 std::string real_strprintf(const std::string &format, int dummy, ...);
151 #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
152
153 bool error(const char *format, ...);
154 void LogException(std::exception* pex, const char* pszThread);
155 void PrintException(std::exception* pex, const char* pszThread);
156 void PrintExceptionContinue(std::exception* pex, const char* pszThread);
157 void ParseString(const std::string& str, char c, std::vector<std::string>& v);
158 std::string FormatMoney(int64 n, bool fPlus=false);
159 bool ParseMoney(const std::string& str, int64& nRet);
160 bool ParseMoney(const char* pszIn, int64& nRet);
161 std::vector<unsigned char> ParseHex(const char* psz);
162 std::vector<unsigned char> ParseHex(const std::string& str);
163 bool IsHex(const std::string& str);
164 std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL);
165 std::string DecodeBase64(const std::string& str);
166 std::string EncodeBase64(const unsigned char* pch, size_t len);
167 std::string EncodeBase64(const std::string& str);
168 void ParseParameters(int argc, const char*const argv[]);
169 bool WildcardMatch(const char* psz, const char* mask);
170 bool WildcardMatch(const std::string& str, const std::string& mask);
171 int GetFilesize(FILE* file);
172 boost::filesystem::path GetDefaultDataDir();
173 const boost::filesystem::path &GetDataDir(bool fNetSpecific = true);
174 boost::filesystem::path GetConfigFile();
175 boost::filesystem::path GetPidFile();
176 void CreatePidFile(const boost::filesystem::path &path, pid_t pid);
177 void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet);
178 bool GetStartOnSystemStartup();
179 bool SetStartOnSystemStartup(bool fAutoStart);
180 void ShrinkDebugFile();
181 int GetRandInt(int nMax);
182 uint64 GetRand(uint64 nMax);
183 uint256 GetRandHash();
184 int64 GetTime();
185 void SetMockTime(int64 nMockTimeIn);
186 int64 GetAdjustedTime();
187 std::string FormatFullVersion();
188 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments);
189 void AddTimeData(const CNetAddr& ip, int64 nTime);
190
191
192
193
194
195
196
197
198
199
200
201 /** Wrapped boost mutex: supports recursive locking, but no waiting  */
202 typedef boost::interprocess::interprocess_recursive_mutex CCriticalSection;
203
204 /** Wrapped boost mutex: supports waiting but not recursive locking */
205 typedef boost::interprocess::interprocess_mutex CWaitableCriticalSection;
206
207 #ifdef DEBUG_LOCKORDER
208 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false);
209 void LeaveCritical();
210 #else
211 void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {}
212 void static inline LeaveCritical() {}
213 #endif
214
215 /** Wrapper around boost::interprocess::scoped_lock */
216 template<typename Mutex>
217 class CMutexLock
218 {
219 private:
220     boost::interprocess::scoped_lock<Mutex> lock;
221 public:
222
223     void Enter(const char* pszName, const char* pszFile, int nLine)
224     {
225         if (!lock.owns())
226         {
227             EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()));
228 #ifdef DEBUG_LOCKCONTENTION
229             if (!lock.try_lock())
230             {
231                 printf("LOCKCONTENTION: %s\n", pszName);
232                 printf("Locker: %s:%d\n", pszFile, nLine);
233 #endif
234             lock.lock();
235 #ifdef DEBUG_LOCKCONTENTION
236             }
237 #endif
238         }
239     }
240
241     void Leave()
242     {
243         if (lock.owns())
244         {
245             lock.unlock();
246             LeaveCritical();
247         }
248     }
249
250     bool TryEnter(const char* pszName, const char* pszFile, int nLine)
251     {
252         if (!lock.owns())
253         {
254             EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()), true);
255             lock.try_lock();
256             if (!lock.owns())
257                 LeaveCritical();
258         }
259         return lock.owns();
260     }
261
262     CMutexLock(Mutex& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) : lock(mutexIn, boost::interprocess::defer_lock)
263     {
264         if (fTry)
265             TryEnter(pszName, pszFile, nLine);
266         else
267             Enter(pszName, pszFile, nLine);
268     }
269
270     ~CMutexLock()
271     {
272         if (lock.owns())
273             LeaveCritical();
274     }
275
276     operator bool()
277     {
278         return lock.owns();
279     }
280
281     boost::interprocess::scoped_lock<Mutex> &GetLock()
282     {
283         return lock;
284     }
285 };
286
287 typedef CMutexLock<CCriticalSection> CCriticalBlock;
288
289 #define LOCK(cs) CCriticalBlock criticalblock(cs, #cs, __FILE__, __LINE__)
290 #define LOCK2(cs1,cs2) CCriticalBlock criticalblock1(cs1, #cs1, __FILE__, __LINE__),criticalblock2(cs2, #cs2, __FILE__, __LINE__)
291 #define TRY_LOCK(cs,name) CCriticalBlock name(cs, #cs, __FILE__, __LINE__, true)
292
293 #define ENTER_CRITICAL_SECTION(cs) \
294     { \
295         EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \
296         (cs).lock(); \
297     }
298
299 #define LEAVE_CRITICAL_SECTION(cs) \
300     { \
301         (cs).unlock(); \
302         LeaveCritical(); \
303     }
304
305 #ifdef MAC_OSX
306 // boost::interprocess::interprocess_semaphore seems to spinlock on OSX; prefer polling instead
307 class CSemaphore
308 {
309 private:
310     CCriticalSection cs;
311     int val;
312
313 public:
314     CSemaphore(int init) : val(init) {}
315
316     void wait() {
317         do {
318             {
319                 LOCK(cs);
320                 if (val>0) {
321                     val--;
322                     return;
323                 }
324             }
325             Sleep(100);
326         } while(1);
327     }
328
329     bool try_wait() {
330         LOCK(cs);
331         if (val>0) {
332             val--;
333             return true;
334         }
335         return false;
336     }
337
338     void post() {
339         LOCK(cs);
340         val++;
341     }
342 };
343 #else
344 typedef boost::interprocess::interprocess_semaphore CSemaphore;
345 #endif
346
347 inline std::string i64tostr(int64 n)
348 {
349     return strprintf("%"PRI64d, n);
350 }
351
352 inline std::string itostr(int n)
353 {
354     return strprintf("%d", n);
355 }
356
357 inline int64 atoi64(const char* psz)
358 {
359 #ifdef _MSC_VER
360     return _atoi64(psz);
361 #else
362     return strtoll(psz, NULL, 10);
363 #endif
364 }
365
366 inline int64 atoi64(const std::string& str)
367 {
368 #ifdef _MSC_VER
369     return _atoi64(str.c_str());
370 #else
371     return strtoll(str.c_str(), NULL, 10);
372 #endif
373 }
374
375 inline int atoi(const std::string& str)
376 {
377     return atoi(str.c_str());
378 }
379
380 inline int roundint(double d)
381 {
382     return (int)(d > 0 ? d + 0.5 : d - 0.5);
383 }
384
385 inline int64 roundint64(double d)
386 {
387     return (int64)(d > 0 ? d + 0.5 : d - 0.5);
388 }
389
390 inline int64 abs64(int64 n)
391 {
392     return (n >= 0 ? n : -n);
393 }
394
395 template<typename T>
396 std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
397 {
398     std::vector<char> rv;
399     static char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
400                                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
401     rv.reserve((itend-itbegin)*3);
402     for(T it = itbegin; it < itend; ++it)
403     {
404         unsigned char val = (unsigned char)(*it);
405         if(fSpaces && it != itbegin)
406             rv.push_back(' ');
407         rv.push_back(hexmap[val>>4]);
408         rv.push_back(hexmap[val&15]);
409     }
410
411     return std::string(rv.begin(), rv.end());
412 }
413
414 inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false)
415 {
416     return HexStr(vch.begin(), vch.end(), fSpaces);
417 }
418
419 template<typename T>
420 void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true)
421 {
422     printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str());
423 }
424
425 inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true)
426 {
427     printf(pszFormat, HexStr(vch, fSpaces).c_str());
428 }
429
430 inline int64 GetPerformanceCounter()
431 {
432     int64 nCounter = 0;
433 #ifdef WIN32
434     QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
435 #else
436     timeval t;
437     gettimeofday(&t, NULL);
438     nCounter = t.tv_sec * 1000000 + t.tv_usec;
439 #endif
440     return nCounter;
441 }
442
443 inline int64 GetTimeMillis()
444 {
445     return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -
446             boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
447 }
448
449 inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime)
450 {
451     time_t n = nTime;
452     struct tm* ptmTime = gmtime(&n);
453     char pszTime[200];
454     strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime);
455     return pszTime;
456 }
457
458 static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC";
459 inline std::string DateTimeStrFormat(int64 nTime)
460 {
461     return DateTimeStrFormat(strTimestampFormat.c_str(), nTime);
462 }
463
464 template<typename T>
465 void skipspaces(T& it)
466 {
467     while (isspace(*it))
468         ++it;
469 }
470
471 inline bool IsSwitchChar(char c)
472 {
473 #ifdef WIN32
474     return c == '-' || c == '/';
475 #else
476     return c == '-';
477 #endif
478 }
479
480 /**
481  * Return string argument or default value
482  *
483  * @param strArg Argument to get (e.g. "-foo")
484  * @param default (e.g. "1")
485  * @return command-line argument or default value
486  */
487 std::string GetArg(const std::string& strArg, const std::string& strDefault);
488
489 /**
490  * Return integer argument or default value
491  *
492  * @param strArg Argument to get (e.g. "-foo")
493  * @param default (e.g. 1)
494  * @return command-line argument (0 if invalid number) or default value
495  */
496 int64 GetArg(const std::string& strArg, int64 nDefault);
497
498 /**
499  * Return boolean argument or default value
500  *
501  * @param strArg Argument to get (e.g. "-foo")
502  * @param default (true or false)
503  * @return command-line argument or default value
504  */
505 bool GetBoolArg(const std::string& strArg, bool fDefault=false);
506
507 /**
508  * Set an argument if it doesn't already have a value
509  *
510  * @param strArg Argument to set (e.g. "-foo")
511  * @param strValue Value (e.g. "1")
512  * @return true if argument gets set, false if it already had a value
513  */
514 bool SoftSetArg(const std::string& strArg, const std::string& strValue);
515
516 /**
517  * Set a boolean argument if it doesn't already have a value
518  *
519  * @param strArg Argument to set (e.g. "-foo")
520  * @param fValue Value (e.g. false)
521  * @return true if argument gets set, false if it already had a value
522  */
523 bool SoftSetBoolArg(const std::string& strArg, bool fValue);
524
525
526
527
528
529
530
531
532
533 // Randomize the stack to help protect against buffer overrun exploits
534 #define IMPLEMENT_RANDOMIZE_STACK(ThreadFn)     \
535     {                                           \
536         static char nLoops;                     \
537         if (nLoops <= 0)                        \
538             nLoops = GetRand(20) + 1;           \
539         if (nLoops-- > 1)                       \
540         {                                       \
541             ThreadFn;                           \
542             return;                             \
543         }                                       \
544     }
545
546
547 template<typename T1>
548 inline uint256 Hash(const T1 pbegin, const T1 pend)
549 {
550     static unsigned char pblank[1];
551     uint256 hash1;
552     SHA256((pbegin == pend ? pblank : (unsigned char*)&pbegin[0]), (pend - pbegin) * sizeof(pbegin[0]), (unsigned char*)&hash1);
553     uint256 hash2;
554     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
555     return hash2;
556 }
557
558 template<typename T1, typename T2>
559 inline uint256 Hash(const T1 p1begin, const T1 p1end,
560                     const T2 p2begin, const T2 p2end)
561 {
562     static unsigned char pblank[1];
563     uint256 hash1;
564     SHA256_CTX ctx;
565     SHA256_Init(&ctx);
566     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
567     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
568     SHA256_Final((unsigned char*)&hash1, &ctx);
569     uint256 hash2;
570     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
571     return hash2;
572 }
573
574 template<typename T1, typename T2, typename T3>
575 inline uint256 Hash(const T1 p1begin, const T1 p1end,
576                     const T2 p2begin, const T2 p2end,
577                     const T3 p3begin, const T3 p3end)
578 {
579     static unsigned char pblank[1];
580     uint256 hash1;
581     SHA256_CTX ctx;
582     SHA256_Init(&ctx);
583     SHA256_Update(&ctx, (p1begin == p1end ? pblank : (unsigned char*)&p1begin[0]), (p1end - p1begin) * sizeof(p1begin[0]));
584     SHA256_Update(&ctx, (p2begin == p2end ? pblank : (unsigned char*)&p2begin[0]), (p2end - p2begin) * sizeof(p2begin[0]));
585     SHA256_Update(&ctx, (p3begin == p3end ? pblank : (unsigned char*)&p3begin[0]), (p3end - p3begin) * sizeof(p3begin[0]));
586     SHA256_Final((unsigned char*)&hash1, &ctx);
587     uint256 hash2;
588     SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
589     return hash2;
590 }
591
592 template<typename T>
593 uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
594 {
595     // Most of the time is spent allocating and deallocating CDataStream's
596     // buffer.  If this ever needs to be optimized further, make a CStaticStream
597     // class with its buffer on the stack.
598     CDataStream ss(nType, nVersion);
599     ss.reserve(10000);
600     ss << obj;
601     return Hash(ss.begin(), ss.end());
602 }
603
604 inline uint160 Hash160(const std::vector<unsigned char>& vch)
605 {
606     uint256 hash1;
607     SHA256(&vch[0], vch.size(), (unsigned char*)&hash1);
608     uint160 hash2;
609     RIPEMD160((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
610     return hash2;
611 }
612
613
614 /** Median filter over a stream of values. 
615  * Returns the median of the last N numbers
616  */
617 template <typename T> class CMedianFilter
618 {
619 private:
620     std::vector<T> vValues;
621     std::vector<T> vSorted;
622     unsigned int nSize;
623 public:
624     CMedianFilter(unsigned int size, T initial_value):
625         nSize(size)
626     {
627         vValues.reserve(size);
628         vValues.push_back(initial_value);
629         vSorted = vValues;
630     }
631     
632     void input(T value)
633     {
634         if(vValues.size() == nSize)
635         {
636             vValues.erase(vValues.begin());
637         }
638         vValues.push_back(value);
639
640         vSorted.resize(vValues.size());
641         std::copy(vValues.begin(), vValues.end(), vSorted.begin());
642         std::sort(vSorted.begin(), vSorted.end());
643     }
644
645     T median() const
646     {
647         int size = vSorted.size();
648         assert(size>0);
649         if(size & 1) // Odd number of elements
650         {
651             return vSorted[size/2];
652         }
653         else // Even number of elements
654         {
655             return (vSorted[size/2-1] + vSorted[size/2]) / 2;
656         }
657     }
658
659     int size() const
660     {
661         return vValues.size();
662     }
663
664     std::vector<T> sorted () const
665     {
666         return vSorted;
667     }
668 };
669
670
671
672
673
674
675
676
677
678
679 // Note: It turns out we might have been able to use boost::thread
680 // by using TerminateThread(boost::thread.native_handle(), 0);
681 #ifdef WIN32
682 typedef HANDLE bitcoin_pthread_t;
683
684 inline bitcoin_pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
685 {
686     DWORD nUnused = 0;
687     HANDLE hthread =
688         CreateThread(
689             NULL,                        // default security
690             0,                           // inherit stack size from parent
691             (LPTHREAD_START_ROUTINE)pfn, // function pointer
692             parg,                        // argument
693             0,                           // creation option, start immediately
694             &nUnused);                   // thread identifier
695     if (hthread == NULL)
696     {
697         printf("Error: CreateThread() returned %d\n", GetLastError());
698         return (bitcoin_pthread_t)0;
699     }
700     if (!fWantHandle)
701     {
702         CloseHandle(hthread);
703         return (bitcoin_pthread_t)-1;
704     }
705     return hthread;
706 }
707
708 inline void SetThreadPriority(int nPriority)
709 {
710     SetThreadPriority(GetCurrentThread(), nPriority);
711 }
712 #else
713 inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
714 {
715     pthread_t hthread = 0;
716     int ret = pthread_create(&hthread, NULL, (void*(*)(void*))pfn, parg);
717     if (ret != 0)
718     {
719         printf("Error: pthread_create() returned %d\n", ret);
720         return (pthread_t)0;
721     }
722     if (!fWantHandle)
723     {
724         pthread_detach(hthread);
725         return (pthread_t)-1;
726     }
727     return hthread;
728 }
729
730 #define THREAD_PRIORITY_LOWEST          PRIO_MAX
731 #define THREAD_PRIORITY_BELOW_NORMAL    2
732 #define THREAD_PRIORITY_NORMAL          0
733 #define THREAD_PRIORITY_ABOVE_NORMAL    0
734
735 inline void SetThreadPriority(int nPriority)
736 {
737     // It's unclear if it's even possible to change thread priorities on Linux,
738     // but we really and truly need it for the generation threads.
739 #ifdef PRIO_THREAD
740     setpriority(PRIO_THREAD, 0, nPriority);
741 #else
742     setpriority(PRIO_PROCESS, 0, nPriority);
743 #endif
744 }
745
746 inline void ExitThread(size_t nExitCode)
747 {
748     pthread_exit((void*)nExitCode);
749 }
750 #endif
751
752
753
754
755
756 inline uint32_t ByteReverse(uint32_t value)
757 {
758     value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
759     return (value<<16) | (value>>16);
760 }
761
762 #endif
763