charconv.h 12.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include <stdlib.h>
#include <algorithm>
#include <climits>
#include <limits>
21 22
#include <system_error>          // NOLINT
#include "lite/utils/variant.h"  // for likely
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

namespace paddle {
namespace lite {
namespace utils {

/*
 * The `std::string` handle can improve the encapsulation, but
 * `const char*` is still needed to improve efficiency in the
 * processing of small strings. This source code gives a simple
 * implementation of the std::from_chars helper function in the
 * C++ 17 standard.
 */
struct from_chars_result {
  const char* ptr{nullptr};
  std::errc ec{};
};

/*
41 42 43
 * Reference:
 * https://github.com/VerizonDigital/json_parser
 *
44 45 46 47 48
 * Most C++ environments use ASCII as the development character
 * set. Array `kAsciiToInt` is the look-up table implementation
 * of the following functions:
 *
 * static inline uint8_t get_char_val(char c) {
49
 *   if (LIKELY(c >= '0' && c <= '9'))
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
 *     return c - '0';
 *   if (c >= 'A' && c <= 'Z')
 *     return 10 + (c - 'A');
 *   if (c >= 'a' && c <= 'z')
 *     return 10 + (c - 'a');
 *   return std::numeric_limits<uint8_t>::max();
 * }
 */
constexpr uint8_t kAsciiToInt[256] = {
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    0 /* 0 */,  1,         2,         3,         4,         5,
    6,          7,         8,         9,         UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, 10 /* A */,
    12,         13,        14,        15,        16,        17,
    18,         19,        20,        21,        22,        23,
    24,         25,        26,        27,        28,        29,
    30,         31,        32,        33,        34,        35,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    10 /* a */, 11,        12,        13,        14,        15,
    16,         17,        18,        19,        20,        21,
    22,         23,        24,        25,        26,        27,
    28,         29,        30,        31,        32,        33,
    34,         35,        UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX, UCHAR_MAX,
    UCHAR_MAX,  UCHAR_MAX, UCHAR_MAX};

103 104
/*
 * function: aton_unsigned
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
 * brief: Convert a string constant to an unsigned integer.
 * parameters:
 *   str(const char*): input string constant.
 *   len(int): bytes of the string.
 *   value(T): result value.
 *   base(int): integer base to use, default to 10.
 * return(from_chars_result):
 *   the error value and the current character pointer.
 */
template <typename T>
from_chars_result aton_unsigned(const char* str,
                                int len,
                                T& value,  // NOLINT
                                int base = 10) {
  from_chars_result result;
  result.ptr = str;

122
  if (UNLIKELY(!str || len <= 0)) {
123 124 125 126
    result.ec = std::errc::invalid_argument;
    return result;
  }
  uint64_t val = 0;
127
  if (UNLIKELY(*str == '-')) {
128 129 130
    result.ec = std::errc::result_out_of_range;
    return result;
  }
131
  if (UNLIKELY(*str == '+')) {
132 133 134 135 136 137
    ++str;
    --len;
  }
  int i = 0;
  for (; i < len; ++i) {
    uint8_t cv = kAsciiToInt[reinterpret_cast<const uint8_t&>(str[i])];
138
    if (UNLIKELY(cv >= base)) {
139 140 141 142 143 144
      value = static_cast<T>(val);
      result.ptr = str + i;
      return result;
    }
    // Handling integer values that may exceed the range represented by the
    // basic type.
145
    if (UNLIKELY(i > std::numeric_limits<uint32_t>::digits10 + 1) &&
146 147 148 149 150 151 152 153
        i == std::numeric_limits<uint64_t>::digits10) {
      uint64_t mx = static_cast<uint64_t>(std::numeric_limits<T>::max());
      if (val > mx / 10 || mx - (val * base) < cv) {
        value = static_cast<T>(std::numeric_limits<T>::max());
        result.ec = std::errc::result_out_of_range;
        return result;
      }
    }
154
    if (LIKELY(i != 10)) {
155 156 157 158
      val *= base;
    }
    val += cv;
  }
159
  if (UNLIKELY(i > std::numeric_limits<T>::digits10 + 1 ||
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
               (i > std::numeric_limits<T>::digits10 &&
                val > static_cast<uint64_t>(std::numeric_limits<T>::max())))) {
    value = static_cast<T>(std::numeric_limits<T>::max());
    result.ec = std::errc::result_out_of_range;
    return result;
  }
  value = static_cast<T>(val);
  return result;
}

/* function: aton_signed
 * brief: Convert a string constant to an signed integer.
 * parameters:
 *   str(const char*): input string constant.
 *   len(int): bytes of the string.
 *   value(T): result value.
 *   base(int): integer base to use, default to 10.
 * return(from_chars_result):
 *   the error value and the current character pointer.
 */
template <typename T>
from_chars_result aton_signed(const char* str,
                              int len,
                              T& value,  // NOLINT
                              int base = 10) {
  from_chars_result result;
  result.ptr = str;

188
  if (UNLIKELY(!str || len <= 0)) {
189 190 191 192 193 194 195 196 197 198 199 200
    result.ec = std::errc::invalid_argument;
    return result;
  }
  uint64_t val = 0;
  bool negative = (*str == '-');
  if (negative || *str == '+') {
    ++str;
    --len;
  }
  int i = 0;
  for (; i < len; ++i) {
    uint8_t cv = kAsciiToInt[reinterpret_cast<const uint8_t&>(str[i])];
201
    if (UNLIKELY(cv >= base)) {
202 203 204 205
      value = static_cast<T>(val);
      result.ptr = str + i;
      return result;
    }
206
    if (LIKELY(i != 0)) {
207 208 209 210
      val *= base;
    }
    val += cv;
  }
211 212
  if (LIKELY(!negative)) {
    if (UNLIKELY(i > std::numeric_limits<T>::digits10 + 1 ||
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                 (i > std::numeric_limits<T>::digits10 &&
                  val > static_cast<int64_t>(std::numeric_limits<T>::max())))) {
      value = static_cast<T>(std::numeric_limits<T>::max());
      result.ec = std::errc::result_out_of_range;
      return result;
    }
    value = static_cast<T>(val);
    return result;
  }
  int64_t ret{static_cast<int64_t>(val)};
  if (negative) {
    ret *= -1;
  }
  if (i > std::numeric_limits<T>::digits10 + 1 ||
      ret < static_cast<int64_t>(std::numeric_limits<T>::min())) {
    value = static_cast<T>(std::numeric_limits<T>::min());
    result.ec = std::errc::result_out_of_range;
    return result;
  }
  value = static_cast<T>(ret);
  return result;
}

/* function: aton_float
 * brief: Convert a string constant to a float digit.
 * parameters:
 *   str(const char*): input string constant.
 *   len(int): bytes of the string.
 *   value(T): result value.
 * return(from_chars_result):
 *   the error value and the current character pointer.
 */
template <typename T>
from_chars_result aton_float(const char* str, int len, T& value) {  // NOLINT
  from_chars_result result;
  result.ptr = str;
  const uint8_t base = 10;

251
  if (UNLIKELY(!str || len <= 0)) {
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    result.ec = std::errc::invalid_argument;
    return result;
  }
  uint64_t lval = 0;
  uint64_t rval = 0;
  uint64_t rdiv = 1;
  bool negative = *str == '-';
  if (negative || *str == '+') {
    ++str;
    --len;
  }
  ssize_t dot_pos = -1;
  int i = 0;
  for (; i < len; ++i) {
    char c = str[i];
    if ('.' == c) {
      dot_pos = i;
      ++i;
      break;
    }
    uint8_t cv = kAsciiToInt[reinterpret_cast<const uint8_t&>(c)];
273
    if (UNLIKELY(cv >= base)) {
274 275 276 277 278 279 280 281 282 283 284 285 286
      value = static_cast<T>(lval);
      result.ptr = str + i;
      return result;
    }
    if (i != 0) {
      lval *= 10;
    }
    lval += cv;
  }
  double val{static_cast<double>(lval)};
  if (-1 != dot_pos) {
    for (; i < len; ++i) {
      uint8_t cv = kAsciiToInt[reinterpret_cast<const uint8_t&>(str[i])];
287
      if (UNLIKELY(cv >= base)) {
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        result.ptr = str + i;
        return result;
      }
      if (i - dot_pos > 1) {
        rval *= 10.0;
      }
      rval += cv;
      rdiv *= 10;
    }
    val += static_cast<double>(rval) / rdiv;
  }

  if (!negative && val > static_cast<double>(std::numeric_limits<T>::max())) {
    value = static_cast<T>(std::numeric_limits<T>::max());
    result.ec = std::errc::result_out_of_range;
    return result;
  }
  if (!negative) {
    value = static_cast<T>(val);
    return result;
  }
  val *= -1;
  if (val < static_cast<double>(-std::numeric_limits<T>::max())) {
    value = static_cast<T>(std::numeric_limits<T>::min());
    result.ec = std::errc::result_out_of_range;
    return result;
  }
  value = static_cast<T>(val);
  return result;
}

// To simplify the number of interfaces, using template type
// deduction here.
template <typename T>
from_chars_result from_chars(const char* first,
                             const char* last,
                             T& value,  // NOLINT
                             int base = 10) = delete;

#define UNSIGNED_FROM_CHARS_INSTANCE(T)                          \
  template <>                                                    \
  inline from_chars_result from_chars<T>(                        \
      const char* first, const char* last, T& value, int base) { \
    return aton_unsigned(first, last - first, value, base);      \
  }
#define SIGNED_FROM_CHARS_INSTANCE(T)                            \
  template <>                                                    \
  inline from_chars_result from_chars<T>(                        \
      const char* first, const char* last, T& value, int base) { \
    return aton_signed(first, last - first, value, base);        \
  }
#define FLOAT_FROM_CHARS_INSTANCE(T)                             \
  template <>                                                    \
  inline from_chars_result from_chars<T>(                        \
      const char* first, const char* last, T& value, int base) { \
    return aton_float(first, last - first, value);               \
  }
UNSIGNED_FROM_CHARS_INSTANCE(uint8_t);
UNSIGNED_FROM_CHARS_INSTANCE(uint16_t);
UNSIGNED_FROM_CHARS_INSTANCE(uint32_t);
UNSIGNED_FROM_CHARS_INSTANCE(uint64_t);
SIGNED_FROM_CHARS_INSTANCE(int8_t);
SIGNED_FROM_CHARS_INSTANCE(int16_t);
SIGNED_FROM_CHARS_INSTANCE(int32_t);
SIGNED_FROM_CHARS_INSTANCE(int64_t);
FLOAT_FROM_CHARS_INSTANCE(double);
FLOAT_FROM_CHARS_INSTANCE(float);
#undef FLOAT_FROM_CHARS_INSTANCE
#undef SIGNED_FROM_CHARS_INSTANCE
#undef UNSIGNED_FROM_CHARS_INSTANCE

}  // namespace utils
}  // namespace lite
}  // namespace paddle