Float16Test.cpp 2.1 KB

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