Home | History | Annotate | Download | only in tests
      1 /*
      2  * Copyright 2016 Google Inc.
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #include "SkAutoPixmapStorage.h"
      9 #include "SkColor.h"
     10 #include "SkHalf.h"
     11 #include "SkOpts.h"
     12 #include "SkPixmap.h"
     13 #include "SkRandom.h"
     14 #include "SkTo.h"
     15 #include "Test.h"
     16 
     17 #include <cmath>
     18 
     19 static bool is_denorm(uint16_t h) {
     20     return (h & 0x7fff) < 0x0400;
     21 }
     22 
     23 static bool is_finite(uint16_t h) {
     24     return (h & 0x7c00) != 0x7c00;
     25 }
     26 
     27 DEF_TEST(SkHalfToFloat_finite_ftz, r) {
     28     for (uint32_t h = 0; h <= 0xffff; h++) {
     29         if (!is_finite(h)) {
     30             // _finite_ftz() only works for values that can be represented as a finite half float.
     31             continue;
     32         }
     33 
     34         // _finite_ftz() may flush denorms to zero.  0.0f will compare == with both +0.0f and -0.0f.
     35         float expected  = SkHalfToFloat(h),
     36               alternate = is_denorm(h) ? 0.0f : expected;
     37 
     38         float actual = SkHalfToFloat_finite_ftz(h)[0];
     39 
     40         REPORTER_ASSERT(r, actual == expected || actual == alternate);
     41     }
     42 }
     43 
     44 DEF_TEST(SkFloatToHalf_finite_ftz, r) {
     45 #if 0
     46     for (uint64_t bits = 0; bits <= 0xffffffff; bits++) {
     47 #else
     48     SkRandom rand;
     49     for (int i = 0; i < 1000000; i++) {
     50         uint32_t bits = rand.nextU();
     51 #endif
     52         float f;
     53         memcpy(&f, &bits, 4);
     54 
     55         uint16_t expected = SkFloatToHalf(f);
     56         if (!is_finite(expected)) {
     57             // _finite_ftz() only works for values that can be represented as a finite half float.
     58             continue;
     59         }
     60 
     61         uint16_t alternate = expected;
     62         if (is_denorm(expected)) {
     63             // _finite_ftz() may flush denorms to zero, and happens to keep the sign bit.
     64             alternate = std::signbit(f) ? 0x8000 : 0x0000;
     65         }
     66 
     67         uint16_t actual = SkFloatToHalf_finite_ftz(Sk4f{f})[0];
     68         // _finite_ftz() may truncate instead of rounding, so it may be one too small.
     69         REPORTER_ASSERT(r, actual == expected  || actual == expected  - 1 ||
     70                            actual == alternate || actual == alternate - 1);
     71     }
     72 }
     73