corda/src/common.h

133 lines
2.2 KiB
C
Raw Normal View History

#ifndef COMMON_H
#define COMMON_H
2007-06-05 00:28:52 +00:00
#include "stdint.h"
2007-06-18 04:25:42 +00:00
#include "stdlib.h"
#include "stdarg.h"
#include "string.h"
#include "stdio.h"
2007-06-29 02:58:48 +00:00
#include "types.h"
2007-06-05 00:28:52 +00:00
#ifdef __i386__
# define LD "%d"
# define LLD "%lld"
#elif defined __x86_64__
# define LD "%ld"
# define LLD "%ld"
#endif
#define NO_RETURN __attribute__((noreturn))
2007-06-20 21:27:22 +00:00
#define LIKELY(v) __builtin_expect((v) != 0, true)
2007-06-20 21:27:22 +00:00
#define UNLIKELY(v) __builtin_expect((v) != 0, false)
2007-06-05 00:28:52 +00:00
#define MACRO_XY(X, Y) X##Y
#define MACRO_MakeNameXY(FX, LINE) MACRO_XY(FX, LINE)
#define MAKE_NAME(FX) MACRO_MakeNameXY(FX, __LINE__)
2007-06-20 17:42:13 +00:00
inline void* operator new(size_t, void* p) throw() { return p; }
2007-06-20 04:26:36 +00:00
namespace vm {
typedef void* object;
const unsigned BytesPerWord = sizeof(uintptr_t);
const unsigned BitsPerWord = BytesPerWord * 8;
const uintptr_t PointerMask
= ((~static_cast<uintptr_t>(0)) / BytesPerWord) * BytesPerWord;
2007-06-22 20:55:11 +00:00
const unsigned LikelyPageSizeInBytes = 4 * 1024;
2007-06-20 04:26:36 +00:00
2007-06-20 17:42:13 +00:00
inline unsigned
max(unsigned a, unsigned b)
{
return (a > b ? a : b);
}
inline unsigned
min(unsigned a, unsigned b)
{
return (a < b ? a : b);
}
inline unsigned
avg(unsigned a, unsigned b)
{
return (a + b) / 2;
}
2007-06-20 17:42:13 +00:00
inline unsigned
pad(unsigned n)
{
unsigned extra = n % BytesPerWord;
return (extra ? n + BytesPerWord - extra : n);
}
inline unsigned
divide(unsigned n, unsigned d)
{
if (n and d > n) return 1;
return (n / d) + (n % d ? 1 : 0);
}
inline bool
powerOfTwo(unsigned n)
{
for (; n > 2; n >>= 1) if (n & 1) return false;
return true;
}
inline unsigned
nextPowerOfTwo(unsigned n)
{
unsigned r = 1;
while (r < n) r <<= 1;
return r;
}
inline unsigned
log(unsigned n)
{
if (n < 3) return 1;
unsigned r = 0;
for (unsigned i = 1; i < n; ++r) i <<= 1;
return r;
}
inline unsigned
wordOf(unsigned i)
{
return i / BitsPerWord;
}
inline unsigned
bitOf(unsigned i)
{
return i % BitsPerWord;
}
inline unsigned
indexOf(unsigned word, unsigned bit)
{
return (word * BitsPerWord) + bit;
}
template <class T>
inline T&
cast(object p, unsigned offset)
{
return *reinterpret_cast<T*>(static_cast<uint8_t*>(p) + offset);
}
template <class T>
inline T*
mask(T* p)
{
return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) & PointerMask);
}
2007-06-20 04:26:36 +00:00
}
#endif//COMMON_H