| OLD | NEW |
| (Empty) | |
| 1 // Copyright (c) 2017 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include <math.h> |
| 6 |
| 7 #include "base/macros.h" |
| 8 #include "testing/gtest/include/gtest/gtest.h" |
| 9 #include "ui/gfx/half_float.h" |
| 10 |
| 11 namespace gfx { |
| 12 |
| 13 class HalfFloatTest : public testing::Test { |
| 14 public: |
| 15 union FloatUIntUnion { |
| 16 // this must come first for the initializations below to work |
| 17 uint32_t fUInt; |
| 18 float fFloat; |
| 19 }; |
| 20 |
| 21 // Convert an IEEE 754 half-float to a float value |
| 22 // that we can do math on. |
| 23 float FromHalfFloat(HalfFloat half_float) { |
| 24 int sign = (half_float & 0x8000) ? -1 : 1; |
| 25 int exponent = (half_float >> 10) & 0x1F; |
| 26 int fraction = half_float & 0x3FF; |
| 27 if (exponent == 0) { |
| 28 return powf(2.0f, -24.0f) * fraction; |
| 29 } else if (exponent == 0x1F) { |
| 30 return sign * 1000000000000.0f; |
| 31 } else { |
| 32 return pow(2.0f, exponent - 25) * (0x400 + fraction); |
| 33 } |
| 34 } |
| 35 |
| 36 HalfFloat ConvertTruth(float f) { |
| 37 if (f < 0.0) |
| 38 return 0x8000 | ConvertTruth(-f); |
| 39 int max = 0x8000; |
| 40 int min = 0; |
| 41 while (max - min > 1) { |
| 42 int mid = (min + max) >> 1; |
| 43 if (FromHalfFloat(mid) > f) { |
| 44 max = mid; |
| 45 } else { |
| 46 min = mid; |
| 47 } |
| 48 } |
| 49 float low = FromHalfFloat(min); |
| 50 float high = FromHalfFloat(min + 1); |
| 51 if (f - low <= high - f) { |
| 52 return min; |
| 53 } else { |
| 54 return min + 1; |
| 55 } |
| 56 } |
| 57 |
| 58 HalfFloat Convert(float f) { |
| 59 HalfFloat ret; |
| 60 FloatToHalfFloat(&f, &ret, 1); |
| 61 return ret; |
| 62 } |
| 63 }; |
| 64 |
| 65 TEST_F(HalfFloatTest, NoCrashTest) { |
| 66 Convert(nanf("")); |
| 67 Convert(1.0E30f); |
| 68 Convert(-1.0E30f); |
| 69 Convert(1.0E-30f); |
| 70 Convert(-1.0E-30f); |
| 71 } |
| 72 |
| 73 TEST_F(HalfFloatTest, SimpleTest) { |
| 74 static float test[] = { |
| 75 0.0f, 1.0f, 10.0f, 1000.0f, 65503.0f, |
| 76 1.0E-3f, 1.0E-6f, 1.0E-20f, 1.0E-44f, |
| 77 }; |
| 78 for (size_t i = 0; i < arraysize(test); i++) { |
| 79 EXPECT_EQ(ConvertTruth(test[i]), Convert(test[i])) << " float = " |
| 80 << test[i]; |
| 81 if (test[i] != 0.0) { |
| 82 EXPECT_EQ(ConvertTruth(-test[i]), Convert(-test[i])) << " float = " |
| 83 << -test[i]; |
| 84 } |
| 85 } |
| 86 } |
| 87 |
| 88 } // namespace |
| OLD | NEW |