Path: blob/master/thirdparty/graphite/src/inc/bits.h
10279 views
// SPDX-License-Identifier: MIT OR MPL-2.0 OR LGPL-2.1-or-later OR GPL-2.0-or-later1// Copyright 2012, SIL International, All rights reserved.23#pragma once45namespace graphite26{789#if defined GRAPHITE2_BUILTINS && (defined __GNUC__ || defined __clang__)1011template<typename T>12inline unsigned int bit_set_count(T v)13{14return __builtin_popcount(v);15}1617template<>18inline unsigned int bit_set_count(int16 v)19{20return __builtin_popcount(static_cast<uint16>(v));21}2223template<>24inline unsigned int bit_set_count(int8 v)25{26return __builtin_popcount(static_cast<uint8>(v));27}2829template<>30inline unsigned int bit_set_count(unsigned long v)31{32return __builtin_popcountl(v);33}3435template<>36inline unsigned int bit_set_count(signed long v)37{38return __builtin_popcountl(v);39}4041template<>42inline unsigned int bit_set_count(unsigned long long v)43{44return __builtin_popcountll(v);45}4647template<>48inline unsigned int bit_set_count(signed long long v)49{50return __builtin_popcountll(v);51}5253#else5455template<typename T>56inline unsigned int bit_set_count(T v)57{58static size_t const ONES = ~0;5960v = v - ((v >> 1) & T(ONES/3)); // temp61v = (v & T(ONES/15*3)) + ((v >> 2) & T(ONES/15*3)); // temp62v = (v + (v >> 4)) & T(ONES/255*15); // temp63return (T)(v * T(ONES/255)) >> (sizeof(T)-1)*8; // count64}6566#endif6768//TODO: Changed these to uintmax_t when we go to C++1169template<int S>70inline size_t _mask_over_val(size_t v)71{72v = _mask_over_val<S/2>(v);73v |= v >> S*4;74return v;75}7677//TODO: Changed these to uintmax_t when we go to C++1178template<>79inline size_t _mask_over_val<1>(size_t v)80{81v |= v >> 1;82v |= v >> 2;83v |= v >> 4;84return v;85}8687template<typename T>88inline T mask_over_val(T v)89{90return T(_mask_over_val<sizeof(T)>(v));91}9293template<typename T>94inline unsigned long next_highest_power2(T v)95{96return _mask_over_val<sizeof(T)>(v-1)+1;97}9899template<typename T>100inline unsigned int log_binary(T v)101{102return bit_set_count(mask_over_val(v))-1;103}104105template<typename T>106inline T has_zero(const T x)107{108return (x - T(~T(0)/255)) & ~x & T(~T(0)/255*128);109}110111template<typename T>112inline T zero_bytes(const T x, unsigned char n)113{114const T t = T(~T(0)/255*n);115return T((has_zero(x^t) >> 7)*n);116}117118#if 0119inline float float_round(float x, uint32 m)120{121*reinterpret_cast<unsigned int *>(&x) &= m;122return *reinterpret_cast<float *>(&x);123}124#endif125126}127128129