logoalt Hacker News

dmitrygrtoday at 7:18 PM0 repliesview on HN

> The correct fix is to bounds check before casting.

This will do wonders for speed. Actually explicitly using the safe isntr might be better. Something like this will happily compile to a single instr and cause you no grief even if the compiler had it out for you with UB. These instrs all clearly define outputs for all inputs (note that said outputs may not match across architectures)

   static inline __attribute__((always_inline)) int f2i(float myFloat) {
      int myInt;

      #if defined(__arm__)
         asm("VCVT.S32.F32 %0, %1":"=r"(myInt), "t"(myFloat));
      #elif defined (__aarch64__)
         asm("FCVTZS %0, %1":"=r"(myInt), "w"(myFloat));
      #elif defined (__x86_64__)
         asm("CVTTSS2SI %0, %1":"=r"(myInt), "x"(myFloat));
      #else
         #if 0 // be boring
            if (myFloat <= TOO_SMALL_FLOAT || myFloat => TOO_BIG_FLOAT)
               abort();
         #else
            #warning "Embrace the UB"
         #endif
         myInt = (int)myFloat;
      #endif
      return myInt;
   }