From 6de4df23e4acc02c5543d61ae274cc35713c0a12 Mon Sep 17 00:00:00 2001
From: Niels Lohmann <mail@nlohmann.me>
Date: Sun, 20 Jan 2019 12:26:01 +0100
Subject: [PATCH] :bug: fixed integer overflow in dump function #1447

Closes #1447.
---
 include/nlohmann/detail/output/serializer.hpp |  2 +-
 single_include/nlohmann/json.hpp              |  2 +-
 test/src/unit-regression.cpp                  | 11 +++++++++--
 3 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp
index b7a0e70c..9994372d 100644
--- a/include/nlohmann/detail/output/serializer.hpp
+++ b/include/nlohmann/detail/output/serializer.hpp
@@ -620,7 +620,7 @@ class serializer
         if (is_negative)
         {
             *buffer_ptr = '-';
-            abs_value = static_cast<number_unsigned_t>(0 - x);
+            abs_value = static_cast<number_unsigned_t>(-1 - x) + 1;
 
             // account one more byte for the minus sign
             n_chars = 1 + count_digits(abs_value);
diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp
index b946b760..9ea8bed3 100644
--- a/single_include/nlohmann/json.hpp
+++ b/single_include/nlohmann/json.hpp
@@ -11510,7 +11510,7 @@ class serializer
         if (is_negative)
         {
             *buffer_ptr = '-';
-            abs_value = static_cast<number_unsigned_t>(0 - x);
+            abs_value = static_cast<number_unsigned_t>(-1 - x) + 1;
 
             // account one more byte for the minus sign
             n_chars = 1 + count_digits(abs_value);
diff --git a/test/src/unit-regression.cpp b/test/src/unit-regression.cpp
index a2d61550..975b9239 100644
--- a/test/src/unit-regression.cpp
+++ b/test/src/unit-regression.cpp
@@ -1742,7 +1742,8 @@ TEST_CASE("regression tests")
         SECTION("test case in issue #1445")
         {
             nlohmann::json dump_test;
-            const int data[] = {
+            const int data[] =
+            {
                 109,  108,  103,  125,  -122, -53,  115,
                 18,   3,    0,    102,  19,   1,    15,
                 -110, 13,   -3,   -1,   -81,  32,   2,
@@ -1761,7 +1762,7 @@ TEST_CASE("regression tests")
                 -54,  -28,  -26
             };
             std::string s;
-            for (int i=0; i<sizeof(data)/sizeof(int); i++)
+            for (int i = 0; i < sizeof(data) / sizeof(int); i++)
             {
                 s += static_cast<char>(data[i]);
             }
@@ -1769,6 +1770,12 @@ TEST_CASE("regression tests")
             dump_test.dump(-1, ' ', true, nlohmann::json::error_handler_t::replace);
         }
     }
+
+    SECTION("issue #1447 - Integer Overflow (OSS-Fuzz 12506)")
+    {
+        json j = json::parse("[-9223372036854775808]");
+        CHECK(j.dump() == "[-9223372036854775808]");
+    }
 }
 
 TEST_CASE("regression tests, exceptions dependent", "[!throws]")