string.c++ 12.2 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21 22

#include "string.h"
Kenton Varda's avatar
Kenton Varda committed
23
#include "debug.h"
Kenton Varda's avatar
Kenton Varda committed
24 25 26 27
#include <stdio.h>
#include <float.h>
#include <errno.h>
#include <stdlib.h>
28 29 30

namespace kj {

31 32 33 34 35
#if _MSC_VER
#pragma warning(disable: 4996)
// Warns that sprintf() is buffer-overrunny. We know that, it's cool.
#endif

Kenton Varda's avatar
Kenton Varda committed
36
String heapString(size_t size) {
37
  char* buffer = _::HeapArrayDisposer::allocate<char>(size + 1);
Kenton Varda's avatar
Kenton Varda committed
38
  buffer[size] = '\0';
39
  return String(buffer, size, _::HeapArrayDisposer::instance);
40 41
}

Kenton Varda's avatar
Kenton Varda committed
42
String heapString(const char* value, size_t size) {
43
  char* buffer = _::HeapArrayDisposer::allocate<char>(size + 1);
44 45
  memcpy(buffer, value, size);
  buffer[size] = '\0';
46
  return String(buffer, size, _::HeapArrayDisposer::instance);
47 48
}

Kenton Varda's avatar
Kenton Varda committed
49
#define HEXIFY_INT(type, format) \
50 51
CappedArray<char, sizeof(type) * 2 + 1> hex(type i) { \
  CappedArray<char, sizeof(type) * 2 + 1> result; \
Kenton Varda's avatar
Kenton Varda committed
52 53 54 55
  result.setSize(sprintf(result.begin(), format, i)); \
  return result; \
}

56
HEXIFY_INT(unsigned char, "%x");
Kenton Varda's avatar
Kenton Varda committed
57 58 59 60 61 62 63
HEXIFY_INT(unsigned short, "%x");
HEXIFY_INT(unsigned int, "%x");
HEXIFY_INT(unsigned long, "%lx");
HEXIFY_INT(unsigned long long, "%llx");

#undef HEXIFY_INT

64
namespace _ {  // private
Kenton Varda's avatar
Kenton Varda committed
65

66 67 68 69
StringPtr Stringifier::operator*(decltype(nullptr)) const {
  return "nullptr";
}

Kenton Varda's avatar
Kenton Varda committed
70 71 72 73 74
StringPtr Stringifier::operator*(bool b) const {
  return b ? StringPtr("true") : StringPtr("false");
}

#define STRINGIFY_INT(type, format) \
75 76
CappedArray<char, sizeof(type) * 3 + 2> Stringifier::operator*(type i) const { \
  CappedArray<char, sizeof(type) * 3 + 2> result; \
Kenton Varda's avatar
Kenton Varda committed
77 78 79 80
  result.setSize(sprintf(result.begin(), format, i)); \
  return result; \
}

81 82
STRINGIFY_INT(signed char, "%d");
STRINGIFY_INT(unsigned char, "%u");
Kenton Varda's avatar
Kenton Varda committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
STRINGIFY_INT(short, "%d");
STRINGIFY_INT(unsigned short, "%u");
STRINGIFY_INT(int, "%d");
STRINGIFY_INT(unsigned int, "%u");
STRINGIFY_INT(long, "%ld");
STRINGIFY_INT(unsigned long, "%lu");
STRINGIFY_INT(long long, "%lld");
STRINGIFY_INT(unsigned long long, "%llu");
STRINGIFY_INT(const void*, "%p");

#undef STRINGIFY_INT

namespace {

// ----------------------------------------------------------------------
// DoubleToBuffer()
// FloatToBuffer()
//    Copied from Protocol Buffers, (C) Google, BSD license.
//    Kenton wrote this code originally.  The following commentary is
//    from the original.
//
//    Description: converts a double or float to a string which, if
//    passed to NoLocaleStrtod(), will produce the exact same original double
//    (except in case of NaN; all NaNs are considered the same value).
//    We try to keep the string short but it's not guaranteed to be as
//    short as possible.
//
//    DoubleToBuffer() and FloatToBuffer() write the text to the given
//    buffer and return it.  The buffer must be at least
//    kDoubleToBufferSize bytes for doubles and kFloatToBufferSize
//    bytes for floats.  kFastToBufferSize is also guaranteed to be large
//    enough to hold either.
//
//    We want to print the value without losing precision, but we also do
//    not want to print more digits than necessary.  This turns out to be
//    trickier than it sounds.  Numbers like 0.2 cannot be represented
//    exactly in binary.  If we print 0.2 with a very large precision,
//    e.g. "%.50g", we get "0.2000000000000000111022302462515654042363167".
//    On the other hand, if we set the precision too low, we lose
//    significant digits when printing numbers that actually need them.
//    It turns out there is no precision value that does the right thing
//    for all numbers.
//
//    Our strategy is to first try printing with a precision that is never
//    over-precise, then parse the result with strtod() to see if it
//    matches.  If not, we print again with a precision that will always
//    give a precise result, but may use more digits than necessary.
//
//    An arguably better strategy would be to use the algorithm described
//    in "How to Print Floating-Point Numbers Accurately" by Steele &
//    White, e.g. as implemented by David M. Gay's dtoa().  It turns out,
//    however, that the following implementation is about as fast as
//    DMG's code.  Furthermore, DMG's code locks mutexes, which means it
//    will not scale well on multi-core machines.  DMG's code is slightly
//    more accurate (in that it will never use more digits than
//    necessary), but this is probably irrelevant for most users.
//
//    Rob Pike and Ken Thompson also have an implementation of dtoa() in
//    third_party/fmt/fltfmt.cc.  Their implementation is similar to this
//    one in that it makes guesses and then uses strtod() to check them.
//    Their implementation is faster because they use their own code to
//    generate the digits in the first place rather than use snprintf(),
//    thus avoiding format string parsing overhead.  However, this makes
//    it considerably more complicated than the following implementation,
//    and it is embedded in a larger library.  If speed turns out to be
//    an issue, we could re-implement this in terms of their
//    implementation.
// ----------------------------------------------------------------------

#ifdef _WIN32
// MSVC has only _snprintf, not snprintf.
//
// MinGW has both snprintf and _snprintf, but they appear to be different
// functions.  The former is buggy.  When invoked like so:
//   char buffer[32];
//   snprintf(buffer, 32, "%.*g\n", FLT_DIG, 1.23e10f);
// it prints "1.23000e+10".  This is plainly wrong:  %g should never print
// trailing zeros after the decimal point.  For some reason this bug only
// occurs with some input values, not all.  In any case, _snprintf does the
// right thing, so we use it.
#define snprintf _snprintf
#endif

inline bool IsNaN(double value) {
  // NaN is never equal to anything, even itself.
  return value != value;
}

// In practice, doubles should never need more than 24 bytes and floats
// should never need more than 14 (including null terminators), but we
// overestimate to be safe.
static const int kDoubleToBufferSize = 32;
static const int kFloatToBufferSize = 24;

static inline bool IsValidFloatChar(char c) {
  return ('0' <= c && c <= '9') ||
         c == 'e' || c == 'E' ||
         c == '+' || c == '-';
}

void DelocalizeRadix(char* buffer) {
  // Fast check:  if the buffer has a normal decimal point, assume no
  // translation is needed.
  if (strchr(buffer, '.') != NULL) return;

  // Find the first unknown character.
  while (IsValidFloatChar(*buffer)) ++buffer;

  if (*buffer == '\0') {
    // No radix character found.
    return;
  }

  // We are now pointing at the locale-specific radix character.  Replace it
  // with '.'.
  *buffer = '.';
  ++buffer;

  if (!IsValidFloatChar(*buffer) && *buffer != '\0') {
    // It appears the radix was a multi-byte character.  We need to remove the
    // extra bytes.
    char* target = buffer;
    do { ++buffer; } while (!IsValidFloatChar(*buffer) && *buffer != '\0');
    memmove(target, buffer, strlen(buffer) + 1);
  }
}

void RemovePlus(char* buffer) {
  // Remove any + characters because they are redundant and ugly.

  for (;;) {
    buffer = strchr(buffer, '+');
    if (buffer == NULL) {
      return;
    }
    memmove(buffer, buffer + 1, strlen(buffer + 1) + 1);
  }
}

222
#if _WIN32
223 224 225 226 227 228 229 230 231 232 233 234
void RemoveE0(char* buffer) {
  // Remove redundant leading 0's after an e, e.g. 1e012. Seems to appear on
  // Windows.

  for (;;) {
    buffer = strstr(buffer, "e0");
    if (buffer == NULL || buffer[2] < '0' || buffer[2] > '9') {
      return;
    }
    memmove(buffer + 1, buffer + 2, strlen(buffer + 2) + 1);
  }
}
235
#endif
236

Kenton Varda's avatar
Kenton Varda committed
237 238 239 240 241 242 243
char* DoubleToBuffer(double value, char* buffer) {
  // DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all
  // platforms these days.  Just in case some system exists where DBL_DIG
  // is significantly larger -- and risks overflowing our buffer -- we have
  // this assert.
  static_assert(DBL_DIG < 20, "DBL_DIG is too big.");

244
  if (value == inf()) {
Kenton Varda's avatar
Kenton Varda committed
245 246
    strcpy(buffer, "inf");
    return buffer;
247
  } else if (value == -inf()) {
Kenton Varda's avatar
Kenton Varda committed
248 249 250 251 252 253 254
    strcpy(buffer, "-inf");
    return buffer;
  } else if (IsNaN(value)) {
    strcpy(buffer, "nan");
    return buffer;
  }

255
  int snprintf_result KJ_UNUSED =
Kenton Varda's avatar
Kenton Varda committed
256 257 258 259
    snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG, value);

  // The snprintf should never overflow because the buffer is significantly
  // larger than the precision we asked for.
260
  KJ_DASSERT(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize);
Kenton Varda's avatar
Kenton Varda committed
261 262 263 264 265 266 267 268 269

  // We need to make parsed_value volatile in order to force the compiler to
  // write it out to the stack.  Otherwise, it may keep the value in a
  // register, and if it does that, it may keep it as a long double instead
  // of a double.  This long double may have extra bits that make it compare
  // unequal to "value" even though it would be exactly equal if it were
  // truncated to a double.
  volatile double parsed_value = strtod(buffer, NULL);
  if (parsed_value != value) {
270
    int snprintf_result2 KJ_UNUSED =
Kenton Varda's avatar
Kenton Varda committed
271 272 273
      snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value);

    // Should never overflow; see above.
274
    KJ_DASSERT(snprintf_result2 > 0 && snprintf_result2 < kDoubleToBufferSize);
Kenton Varda's avatar
Kenton Varda committed
275 276 277 278
  }

  DelocalizeRadix(buffer);
  RemovePlus(buffer);
279 280 281
#if _WIN32
  RemoveE0(buffer);
#endif // _WIN32
Kenton Varda's avatar
Kenton Varda committed
282 283 284 285 286 287 288
  return buffer;
}

bool safe_strtof(const char* str, float* value) {
  char* endptr;
  errno = 0;  // errno only gets set on errors
#if defined(_WIN32) || defined (__hpux)  // has no strtof()
289
  *value = static_cast<float>(strtod(str, &endptr));
Kenton Varda's avatar
Kenton Varda committed
290 291 292 293 294 295 296 297 298 299 300 301 302
#else
  *value = strtof(str, &endptr);
#endif
  return *str != 0 && *endptr == 0 && errno == 0;
}

char* FloatToBuffer(float value, char* buffer) {
  // FLT_DIG is 6 for IEEE-754 floats, which are used on almost all
  // platforms these days.  Just in case some system exists where FLT_DIG
  // is significantly larger -- and risks overflowing our buffer -- we have
  // this assert.
  static_assert(FLT_DIG < 10, "FLT_DIG is too big");

303
  if (value == inf()) {
Kenton Varda's avatar
Kenton Varda committed
304 305
    strcpy(buffer, "inf");
    return buffer;
306
  } else if (value == -inf()) {
Kenton Varda's avatar
Kenton Varda committed
307 308 309 310 311 312 313
    strcpy(buffer, "-inf");
    return buffer;
  } else if (IsNaN(value)) {
    strcpy(buffer, "nan");
    return buffer;
  }

314
  int snprintf_result KJ_UNUSED =
Kenton Varda's avatar
Kenton Varda committed
315 316 317 318
    snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG, value);

  // The snprintf should never overflow because the buffer is significantly
  // larger than the precision we asked for.
319
  KJ_DASSERT(snprintf_result > 0 && snprintf_result < kFloatToBufferSize);
Kenton Varda's avatar
Kenton Varda committed
320 321 322

  float parsed_value;
  if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
323
    int snprintf_result2 KJ_UNUSED =
Kenton Varda's avatar
Kenton Varda committed
324 325 326
      snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value);

    // Should never overflow; see above.
327
    KJ_DASSERT(snprintf_result2 > 0 && snprintf_result2 < kFloatToBufferSize);
Kenton Varda's avatar
Kenton Varda committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  }

  DelocalizeRadix(buffer);
  RemovePlus(buffer);
  return buffer;
}

}  // namespace

CappedArray<char, kFloatToBufferSize> Stringifier::operator*(float f) const {
  CappedArray<char, kFloatToBufferSize> result;
  result.setSize(strlen(FloatToBuffer(f, result.begin())));
  return result;
}

CappedArray<char, kDoubleToBufferSize> Stringifier::operator*(double f) const {
  CappedArray<char, kDoubleToBufferSize> result;
  result.setSize(strlen(DoubleToBuffer(f, result.begin())));
  return result;
}

349
}  // namespace _ (private)
350
}  // namespace kj