1 // Tencent is pleased to support the open source community by making RapidJSON available.
3 // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
5 // Licensed under the MIT License (the "License"); you may not use this file except
6 // in compliance with the License. You may obtain a copy of the License at
8 // http://opensource.org/licenses/MIT
10 // Unless required by applicable law or agreed to in writing, software distributed
11 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
13 // specific language governing permissions and limitations under the License.
16 #include "rapidjson/internal/itoa.h"
20 RAPIDJSON_DIAG_OFF(type-limits)
23 using namespace rapidjson::internal;
30 struct Traits<uint32_t> {
31 enum { kBufferSize = 11 };
32 enum { kMaxDigit = 10 };
33 static uint32_t Negate(uint32_t x) { return x; }
37 struct Traits<int32_t> {
38 enum { kBufferSize = 12 };
39 enum { kMaxDigit = 10 };
40 static int32_t Negate(int32_t x) { return -x; }
44 struct Traits<uint64_t> {
45 enum { kBufferSize = 21 };
46 enum { kMaxDigit = 20 };
47 static uint64_t Negate(uint64_t x) { return x; }
51 struct Traits<int64_t> {
52 enum { kBufferSize = 22 };
53 enum { kMaxDigit = 20 };
54 static int64_t Negate(int64_t x) { return -x; }
58 static void VerifyValue(T value, void(*f)(T, char*), char* (*g)(T, char*)) {
59 char buffer1[Traits<T>::kBufferSize];
60 char buffer2[Traits<T>::kBufferSize];
63 *g(value, buffer2) = '\0';
66 EXPECT_STREQ(buffer1, buffer2);
70 static void Verify(void(*f)(T, char*), char* (*g)(T, char*)) {
72 VerifyValue<T>(0, f, g);
73 VerifyValue<T>(std::numeric_limits<T>::min(), f, g);
74 VerifyValue<T>(std::numeric_limits<T>::max(), f, g);
76 // 2^n - 1, 2^n, 10^n - 1, 10^n until overflow
77 for (uint32_t power = 2; power <= 10; power += 8) {
80 VerifyValue<T>(i - 1, f, g);
81 VerifyValue<T>(i, f, g);
82 if (std::numeric_limits<T>::min() < 0) {
83 VerifyValue<T>(Traits<T>::Negate(i), f, g);
84 VerifyValue<T>(Traits<T>::Negate(i + 1), f, g);
87 if (i > static_cast<T>(std::numeric_limits<T>::max() / static_cast<T>(power)))
94 static void u32toa_naive(uint32_t value, char* buffer) {
98 *p++ = static_cast<char>(char(value % 10) + '0');
109 static void i32toa_naive(int32_t value, char* buffer) {
110 uint32_t u = static_cast<uint32_t>(value);
115 u32toa_naive(u, buffer);
118 static void u64toa_naive(uint64_t value, char* buffer) {
122 *p++ = static_cast<char>(char(value % 10) + '0');
133 static void i64toa_naive(int64_t value, char* buffer) {
134 uint64_t u = static_cast<uint64_t>(value);
139 u64toa_naive(u, buffer);
143 Verify(u32toa_naive, u32toa);
147 Verify(i32toa_naive, i32toa);
151 Verify(u64toa_naive, u64toa);
155 Verify(i64toa_naive, i64toa);