templates.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
  3. */
  4. #include <gtest/gtest.h>
  5. #include <uavcan/util/templates.hpp>
  6. #include <limits>
  7. struct NonConvertible { };
  8. struct ConvertibleToBool
  9. {
  10. const bool value;
  11. ConvertibleToBool(bool value) : value(value) { }
  12. operator bool() const { return value; }
  13. bool operator!() const { return !value; }
  14. };
  15. struct NonDefaultConstructible
  16. {
  17. NonDefaultConstructible(int) { }
  18. };
  19. TEST(Util, CoerceOrFallback)
  20. {
  21. using uavcan::coerceOrFallback;
  22. ASSERT_FALSE(coerceOrFallback<bool>(NonConvertible()));
  23. ASSERT_TRUE(coerceOrFallback<bool>(NonConvertible(), true));
  24. ASSERT_EQ(0, coerceOrFallback<long>(NonConvertible()));
  25. ASSERT_EQ(9000, coerceOrFallback<long>(NonConvertible(), 9000));
  26. ASSERT_TRUE(coerceOrFallback<bool>(ConvertibleToBool(true)));
  27. ASSERT_TRUE(coerceOrFallback<bool>(ConvertibleToBool(true), false));
  28. ASSERT_FALSE(coerceOrFallback<bool>(ConvertibleToBool(false)));
  29. ASSERT_FALSE(coerceOrFallback<bool>(ConvertibleToBool(false), true));
  30. ASSERT_EQ(1, coerceOrFallback<long>(ConvertibleToBool(true)));
  31. ASSERT_EQ(0, coerceOrFallback<long>(ConvertibleToBool(false), -100));
  32. //coerceOrFallback<NonDefaultConstructible>(ConvertibleToBool(true)); // Will fail to compile
  33. coerceOrFallback<NonDefaultConstructible>(NonConvertible(), NonDefaultConstructible(64));
  34. }
  35. TEST(Util, FloatClassification)
  36. {
  37. // NAN
  38. ASSERT_TRUE(uavcan::isNaN(std::numeric_limits<float>::quiet_NaN()));
  39. ASSERT_FALSE(uavcan::isNaN(std::numeric_limits<double>::infinity()));
  40. ASSERT_FALSE(uavcan::isNaN(std::numeric_limits<long double>::infinity()));
  41. ASSERT_FALSE(uavcan::isNaN(123.456));
  42. // INF
  43. ASSERT_TRUE(uavcan::isInfinity(std::numeric_limits<float>::infinity()));
  44. ASSERT_TRUE(uavcan::isInfinity(-std::numeric_limits<long double>::infinity()));
  45. ASSERT_FALSE(uavcan::isInfinity(std::numeric_limits<float>::quiet_NaN()));
  46. ASSERT_FALSE(uavcan::isInfinity(-0.1L));
  47. // Signbit
  48. ASSERT_FALSE(uavcan::getSignBit(12));
  49. ASSERT_TRUE(uavcan::getSignBit(-std::numeric_limits<long double>::infinity()));
  50. ASSERT_FALSE(uavcan::getSignBit(std::numeric_limits<float>::infinity()));
  51. ASSERT_TRUE(uavcan::getSignBit(-0.0)); // Negative zero
  52. }