overflow.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // ArduinoJson - arduinojson.org
  2. // Copyright Benoit Blanchon 2014-2019
  3. // MIT License
  4. #include <ArduinoJson.h>
  5. #include <catch.hpp>
  6. template <typename TOut, typename TIn>
  7. void shouldBeOk(TIn value) {
  8. StaticJsonDocument<1> doc;
  9. JsonVariant var = doc.to<JsonVariant>();
  10. var.set(value);
  11. REQUIRE(var.as<TOut>() == TOut(value));
  12. }
  13. template <typename TOut, typename TIn>
  14. void shouldOverflow(TIn value) {
  15. StaticJsonDocument<1> doc;
  16. JsonVariant var = doc.to<JsonVariant>();
  17. var.set(value);
  18. REQUIRE(var.as<TOut>() == 0);
  19. REQUIRE(var.is<TOut>() == false);
  20. }
  21. TEST_CASE("Handle integer overflow in stored integer") {
  22. SECTION("int8_t") {
  23. // ok
  24. shouldBeOk<int8_t>(-128);
  25. shouldBeOk<int8_t>(42.0);
  26. shouldBeOk<int8_t>(127);
  27. // too low
  28. shouldOverflow<int8_t>(-128.1);
  29. shouldOverflow<int8_t>(-129);
  30. // too high
  31. shouldOverflow<int8_t>(128);
  32. shouldOverflow<int8_t>(127.1);
  33. }
  34. SECTION("int16_t") {
  35. // ok
  36. shouldBeOk<int16_t>(-32768);
  37. shouldBeOk<int16_t>(-32767.9);
  38. shouldBeOk<int16_t>(32766.9);
  39. shouldBeOk<int16_t>(32767);
  40. // too low
  41. shouldOverflow<int16_t>(-32768.1);
  42. shouldOverflow<int16_t>(-32769);
  43. // too high
  44. shouldOverflow<int16_t>(32767.1);
  45. shouldOverflow<int16_t>(32768);
  46. }
  47. SECTION("uint8_t") {
  48. // ok
  49. shouldBeOk<uint8_t>(1);
  50. shouldBeOk<uint8_t>(42.0);
  51. shouldBeOk<uint8_t>(255);
  52. // too low
  53. shouldOverflow<uint8_t>(-1);
  54. shouldOverflow<uint8_t>(-0.1);
  55. // to high
  56. shouldOverflow<uint8_t>(255.1);
  57. shouldOverflow<uint8_t>(256);
  58. shouldOverflow<uint8_t>(257);
  59. }
  60. }