robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
87b5062f94
master
1// uncrustify:off 2#include <math.h> 3// uncrustify:on 4#include <limits.h> 5#include <stdint.h> 6#include <string.h> 7 8#ifdef HAVE_BITSCANFORWARD64 9# include <intrin.h> // Required for _BitScanForward64 10#endif 11 12#include "nvim/math.h" 13#include "nvim/vim_defs.h" 14 15#include "math.c.generated.h" 16 17int xfpclassify (double d ) 18FUNC_ATTR_CONST 19{ 20uint64_t m ; 21 22memcpy (& m ,& d ,sizeof (m )); 23int e = 0x7ff & (m >>52 ); 24m = 0xfffffffffffffULL & m ; 25 26switch (e ) { 27default : 28return FP_NORMAL ; 29case 0x000 : 30return m ?FP_SUBNORMAL :FP_ZERO ; 31case 0x7ff : 32return m ?FP_NAN :FP_INFINITE ; 33 } 34} 35 36int xisinf (double d ) 37FUNC_ATTR_CONST 38{ 39return FP_INFINITE == xfpclassify (d ); 40} 41 42int xisnan (double d ) 43FUNC_ATTR_CONST 44{ 45return FP_NAN == xfpclassify (d ); 46} 47 48/// Count trailing zeroes at the end of bit field. 49int xctz (uint64_t x ) 50{ 51// If x == 0, that means all bits are zeroes. 52if (x == 0 ) { 53return 8 * sizeof (x ); 54 } 55 56// Use compiler builtin if possible. 57#if defined(__clang__ )|| (defined(__GNUC__ )&& (__GNUC__ >=4 )) 58return __builtin_ctzll (x ); 59#elif defined(HAVE_BITSCANFORWARD64 ) 60unsigned long index ; 61_BitScanForward64 (& index ,x ); 62return (int )index ; 63#else 64int count = 0 ; 65// Set x's trailing zeroes to ones and zero the rest. 66x = (x ^ (x - 1 )) >>1 ; 67 68// Increment count until there are just zero bits remaining. 69while (x ) { 70count ++ ; 71x >>=1 ; 72 } 73 74return count ; 75#endif 76} 77 78/// Count number of set bits in bit field. 79unsigned xpopcount (uint64_t x ) 80{ 81// Use compiler builtin if possible. 82#ifdef __NetBSD__ 83return popcount64 (x ); 84#elif defined(__clang__ )|| defined(__GNUC__ ) 85return (unsigned )__builtin_popcountll (x ); 86#else 87unsigned count = 0 ; 88for (;x != 0 ;x >>=1 ) { 89if (x & 1 ) { 90count ++ ; 91 } 92 } 93return count ; 94#endif 95} 96 97/// For overflow detection, add a digit safely to an int value. 98int vim_append_digit_int (int * value ,int digit ) 99{ 100int x = * value ; 101if (x > ((INT_MAX - digit ) /10 )) { 102return FAIL ; 103 } 104* value = x * 10 + digit ; 105return OK ; 106} 107 108/// Return something that fits into an int. 109int trim_to_int (int64_t x ) 110{ 111return x > INT_MAX ?INT_MAX :x < INT_MIN ?INT_MIN : (int )x ; 112}