1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/jitcraft/Utility.h Mon Jun 25 02:57:28 2012 -0700
1.3 @@ -0,0 +1,105 @@
1.4 +/*
1.5 + * Copyright (C) 2012 David Anderson
1.6 + *
1.7 + * This file is part of JITCraft.
1.8 + *
1.9 + * JITCraft is free software: you can redistribute it and/or modify it under
1.10 + * the terms of the GNU General Public License as published by the Free
1.11 + * Software Foundation, either version 3 of the License, or (at your option)
1.12 + * any later version.
1.13 + *
1.14 + * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
1.15 + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.16 + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
1.17 + *
1.18 + * You should have received a copy of the GNU General Public License along with
1.19 + * JITCraft. If not, see http://www.gnu.org/licenses/.
1.20 + */
1.21 +#ifndef _include_jitcraft_utility_h_
1.22 +#define _include_jitcraft_utility_h_
1.23 +
1.24 +#include <assert.h>
1.25 +#include <intrin.h>
1.26 +
1.27 +namespace jc {
1.28 +
1.29 +static const size_t kMallocAlignment = sizeof(void *) * 2;
1.30 +
1.31 +template <typename T>
1.32 +class AutoVec
1.33 +{
1.34 + T *t_;
1.35 +
1.36 + public:
1.37 + AutoVec()
1.38 + : t_(NULL)
1.39 + {
1.40 + }
1.41 + AutoVec(T *t)
1.42 + : t_(t)
1.43 + {
1.44 + }
1.45 + ~AutoVec() {
1.46 + delete [] t_;
1.47 + }
1.48 + operator T *() {
1.49 + return t_;
1.50 + }
1.51 + void operator =(T *t) {
1.52 + if (t_)
1.53 + delete [] t_;
1.54 + t_ = t;
1.55 + }
1.56 +};
1.57 +
1.58 +static inline size_t
1.59 +Log2(size_t number)
1.60 +{
1.61 + assert(number != 0);
1.62 +
1.63 + unsigned long rval;
1.64 + _BitScanReverse(&rval, number);
1.65 + return rval;
1.66 +}
1.67 +
1.68 +static inline bool
1.69 +IsPowerOfTwo(size_t value)
1.70 +{
1.71 + if (value == 0)
1.72 + return false;
1.73 + return !(value & (value - 1));
1.74 +}
1.75 +
1.76 +static inline size_t
1.77 +Align(size_t count, size_t alignment)
1.78 +{
1.79 + assert(IsPowerOfTwo(alignment));
1.80 + return count + (alignment - (count % alignment)) % alignment;
1.81 +}
1.82 +
1.83 +static inline bool
1.84 +IsUint32AddSafe(unsigned a, unsigned b)
1.85 +{
1.86 + unsigned log2_a = Log2(a);
1.87 + unsigned log2_b = Log2(b);
1.88 + return (log2_a < sizeof(unsigned) * 8) &&
1.89 + (log2_b < sizeof(unsigned) * 8);
1.90 +}
1.91 +
1.92 +static inline bool
1.93 +IsUint32MultiplySafe(unsigned a, unsigned b)
1.94 +{
1.95 + if (a <= 1 || b <= 1)
1.96 + return true;
1.97 +
1.98 + unsigned log2_a = Log2(a);
1.99 + unsigned log2_b = Log2(b);
1.100 + return log2_a + log2_b <= sizeof(unsigned) * 8;
1.101 +}
1.102 +
1.103 +#define ARRAY_LENGTH(array) (sizeof(array) / sizeof(array[0]))
1.104 +#define STATIC_ASSERT(cond) extern int static_assert_f(int a[(cond) ? 1 : -1])
1.105 +
1.106 +}
1.107 +
1.108 +#endif // _include_jitcraft_utility_h_