parseInteger.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2021
  3. // MIT License
  4. #include <stdint.h>
  5. #include <ArduinoJson/Numbers/parseNumber.hpp>
  6. #include <ArduinoJson/Variant/VariantImpl.hpp>
  7. #include <catch.hpp>
  8. using namespace ARDUINOJSON_NAMESPACE;
  9. template <typename T>
  10. void checkInteger(const char* input, T expected) {
  11. CAPTURE(input);
  12. T actual = parseNumber<T>(input);
  13. REQUIRE(expected == actual);
  14. }
  15. TEST_CASE("parseNumber<int8_t>()") {
  16. checkInteger<int8_t>("-128", -128);
  17. checkInteger<int8_t>("127", 127);
  18. checkInteger<int8_t>("+127", 127);
  19. checkInteger<int8_t>("3.14", 3);
  20. checkInteger<int8_t>("x42", 0);
  21. checkInteger<int8_t>("128", 0); // overflow
  22. checkInteger<int8_t>("-129", 0); // overflow
  23. }
  24. TEST_CASE("parseNumber<int16_t>()") {
  25. checkInteger<int16_t>("-32768", -32768);
  26. checkInteger<int16_t>("32767", 32767);
  27. checkInteger<int16_t>("+32767", 32767);
  28. checkInteger<int16_t>("3.14", 3);
  29. checkInteger<int16_t>("x42", 0);
  30. checkInteger<int16_t>("-32769", 0); // overflow
  31. checkInteger<int16_t>("32768", 0); // overflow
  32. }
  33. TEST_CASE("parseNumber<int32_t>()") {
  34. checkInteger<int32_t>("-2147483648", (-2147483647 - 1));
  35. checkInteger<int32_t>("2147483647", 2147483647);
  36. checkInteger<int32_t>("+2147483647", 2147483647);
  37. checkInteger<int32_t>("3.14", 3);
  38. checkInteger<int32_t>("x42", 0);
  39. checkInteger<int32_t>("-2147483649", 0); // overflow
  40. checkInteger<int32_t>("2147483648", 0); // overflow
  41. }
  42. TEST_CASE("parseNumber<uint8_t>()") {
  43. checkInteger<uint8_t>("0", 0);
  44. checkInteger<uint8_t>("255", 255);
  45. checkInteger<uint8_t>("+255", 255);
  46. checkInteger<uint8_t>("3.14", 3);
  47. checkInteger<uint8_t>("x42", 0);
  48. checkInteger<uint8_t>("-1", 0);
  49. checkInteger<uint8_t>("256", 0);
  50. }
  51. TEST_CASE("parseNumber<uint16_t>()") {
  52. checkInteger<uint16_t>("0", 0);
  53. checkInteger<uint16_t>("65535", 65535);
  54. checkInteger<uint16_t>("+65535", 65535);
  55. checkInteger<uint16_t>("3.14", 3);
  56. // checkInteger<uint16_t>(" 42", 0);
  57. checkInteger<uint16_t>("x42", 0);
  58. checkInteger<uint16_t>("-1", 0);
  59. checkInteger<uint16_t>("65536", 0);
  60. }