• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "src/base/SkHalf.h"
9 #include "src/base/SkRandom.h"
10 #include "src/base/SkVx.h"
11 #include "tests/Test.h"
12 
13 #include <cmath>
14 #include <cstdint>
15 #include <cstring>
16 
is_denorm(uint16_t h)17 static bool is_denorm(uint16_t h) {
18     return (h & 0x7fff) < 0x0400;
19 }
20 
is_finite(uint16_t h)21 static bool is_finite(uint16_t h) {
22     return (h & 0x7c00) != 0x7c00;
23 }
24 
DEF_TEST(SkHalfToFloat_finite_ftz,r)25 DEF_TEST(SkHalfToFloat_finite_ftz, r) {
26     for (uint32_t h = 0; h <= 0xffff; h++) {
27         if (!is_finite(h)) {
28             // _finite_ftz() only works for values that can be represented as a finite half float.
29             continue;
30         }
31 
32         // _finite_ftz() may flush denorms to zero.  0.0f will compare == with both +0.0f and -0.0f.
33         float expected  = SkHalfToFloat(h),
34               alternate = is_denorm(h) ? 0.0f : expected;
35 
36         float actual = SkHalfToFloat_finite_ftz(h)[0];
37 
38         REPORTER_ASSERT(r, actual == expected || actual == alternate);
39     }
40 }
41 
DEF_TEST(SkFloatToHalf_finite_ftz,r)42 DEF_TEST(SkFloatToHalf_finite_ftz, r) {
43 #if 0
44     for (uint64_t bits = 0; bits <= 0xffffffff; bits++) {
45 #else
46     SkRandom rand;
47     for (int i = 0; i < 1000000; i++) {
48         uint32_t bits = rand.nextU();
49 #endif
50         float f;
51         memcpy(&f, &bits, 4);
52 
53         uint16_t expected = SkFloatToHalf(f);
54         if (!is_finite(expected)) {
55             // _finite_ftz() only works for values that can be represented as a finite half float.
56             continue;
57         }
58 
59         uint16_t alternate = expected;
60         if (is_denorm(expected)) {
61             // _finite_ftz() may flush denorms to zero, and happens to keep the sign bit.
62             alternate = std::signbit(f) ? 0x8000 : 0x0000;
63         }
64 
65         uint16_t actual = SkFloatToHalf_finite_ftz(skvx::float4{f})[0];
66         // _finite_ftz() may truncate instead of rounding, so it may be one too small.
67         REPORTER_ASSERT(r, actual == expected  || actual == expected  - 1 ||
68                            actual == alternate || actual == alternate - 1);
69     }
70 }
71