util.h
Go to the documentation of this file.
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef FLATBUFFERS_UTIL_H_
18 #define FLATBUFFERS_UTIL_H_
19 
20 #include "flatbuffers/base.h"
21 
22 #include <errno.h>
23 
24 #ifndef FLATBUFFERS_PREFER_PRINTF
25 # include <sstream>
26 #else // FLATBUFFERS_PREFER_PRINTF
27 # include <float.h>
28 # include <stdio.h>
29 #endif // FLATBUFFERS_PREFER_PRINTF
30 
31 #include <iomanip>
32 #include <string>
33 
34 namespace flatbuffers {
35 
36 // @locale-independent functions for ASCII characters set.
37 
38 // Check that integer scalar is in closed range: (a <= x <= b)
39 // using one compare (conditional branch) operator.
40 template<typename T> inline bool check_in_range(T x, T a, T b) {
41  // (Hacker's Delight): `a <= x <= b` <=> `(x-a) <={u} (b-a)`.
42  FLATBUFFERS_ASSERT(a <= b); // static_assert only if 'a' & 'b' templated
43  typedef typename flatbuffers::make_unsigned<T>::type U;
44  return (static_cast<U>(x - a) <= static_cast<U>(b - a));
45 }
46 
47 // Case-insensitive isalpha
48 inline bool is_alpha(char c) {
49  // ASCII only: alpha to upper case => reset bit 0x20 (~0x20 = 0xDF).
50  return check_in_range(c & 0xDF, 'a' & 0xDF, 'z' & 0xDF);
51 }
52 
53 // Check (case-insensitive) that `c` is equal to alpha.
54 inline bool is_alpha_char(char c, char alpha) {
56  // ASCII only: alpha to upper case => reset bit 0x20 (~0x20 = 0xDF).
57  return ((c & 0xDF) == (alpha & 0xDF));
58 }
59 
60 // https://en.cppreference.com/w/cpp/string/byte/isxdigit
61 // isdigit and isxdigit are the only standard narrow character classification
62 // functions that are not affected by the currently installed C locale. although
63 // some implementations (e.g. Microsoft in 1252 codepage) may classify
64 // additional single-byte characters as digits.
65 inline bool is_digit(char c) { return check_in_range(c, '0', '9'); }
66 
67 inline bool is_xdigit(char c) {
68  // Replace by look-up table.
69  return is_digit(c) || check_in_range(c & 0xDF, 'a' & 0xDF, 'f' & 0xDF);
70 }
71 
72 // Case-insensitive isalnum
73 inline bool is_alnum(char c) { return is_alpha(c) || is_digit(c); }
74 
75 // @end-locale-independent functions for ASCII character set
76 
77 #ifdef FLATBUFFERS_PREFER_PRINTF
78 template<typename T> size_t IntToDigitCount(T t) {
79  size_t digit_count = 0;
80  // Count the sign for negative numbers
81  if (t < 0) digit_count++;
82  // Count a single 0 left of the dot for fractional numbers
83  if (-1 < t && t < 1) digit_count++;
84  // Count digits until fractional part
85  T eps = std::numeric_limits<float>::epsilon();
86  while (t <= (-1 + eps) || (1 - eps) <= t) {
87  t /= 10;
88  digit_count++;
89  }
90  return digit_count;
91 }
92 
93 template<typename T> size_t NumToStringWidth(T t, int precision = 0) {
94  size_t string_width = IntToDigitCount(t);
95  // Count the dot for floating point numbers
96  if (precision) string_width += (precision + 1);
97  return string_width;
98 }
99 
100 template<typename T>
101 std::string NumToStringImplWrapper(T t, const char *fmt, int precision = 0) {
102  size_t string_width = NumToStringWidth(t, precision);
103  std::string s(string_width, 0x00);
104  // Allow snprintf to use std::string trailing null to detect buffer overflow
105  snprintf(const_cast<char *>(s.data()), (s.size() + 1), fmt, precision, t);
106  return s;
107 }
108 #endif // FLATBUFFERS_PREFER_PRINTF
109 
110 // Convert an integer or floating point value to a string.
111 // In contrast to std::stringstream, "char" values are
112 // converted to a string of digits, and we don't use scientific notation.
113 template<typename T> std::string NumToString(T t) {
114  // clang-format off
115 
116  #ifndef FLATBUFFERS_PREFER_PRINTF
117  std::stringstream ss;
118  ss << t;
119  return ss.str();
120  #else // FLATBUFFERS_PREFER_PRINTF
121  auto v = static_cast<long long>(t);
122  return NumToStringImplWrapper(v, "%.*lld");
123  #endif // FLATBUFFERS_PREFER_PRINTF
124  // clang-format on
125 }
126 // Avoid char types used as character data.
127 template<> inline std::string NumToString<signed char>(signed char t) {
128  return NumToString(static_cast<int>(t));
129 }
130 template<> inline std::string NumToString<unsigned char>(unsigned char t) {
131  return NumToString(static_cast<int>(t));
132 }
133 #if defined(FLATBUFFERS_CPP98_STL)
134 template<> inline std::string NumToString<long long>(long long t) {
135  char buf[21]; // (log((1 << 63) - 1) / log(10)) + 2
136  snprintf(buf, sizeof(buf), "%lld", t);
137  return std::string(buf);
138 }
139 
140 template<>
141 inline std::string NumToString<unsigned long long>(unsigned long long t) {
142  char buf[22]; // (log((1 << 63) - 1) / log(10)) + 1
143  snprintf(buf, sizeof(buf), "%llu", t);
144  return std::string(buf);
145 }
146 #endif // defined(FLATBUFFERS_CPP98_STL)
147 
148 // Special versions for floats/doubles.
149 template<typename T> std::string FloatToString(T t, int precision) {
150  // clang-format off
151 
152  #ifndef FLATBUFFERS_PREFER_PRINTF
153  // to_string() prints different numbers of digits for floats depending on
154  // platform and isn't available on Android, so we use stringstream
155  std::stringstream ss;
156  // Use std::fixed to suppress scientific notation.
157  ss << std::fixed;
158  // Default precision is 6, we want that to be higher for doubles.
159  ss << std::setprecision(precision);
160  ss << t;
161  auto s = ss.str();
162  #else // FLATBUFFERS_PREFER_PRINTF
163  auto v = static_cast<double>(t);
164  auto s = NumToStringImplWrapper(v, "%0.*f", precision);
165  #endif // FLATBUFFERS_PREFER_PRINTF
166  // clang-format on
167  // Sadly, std::fixed turns "1" into "1.00000", so here we undo that.
168  auto p = s.find_last_not_of('0');
169  if (p != std::string::npos) {
170  // Strip trailing zeroes. If it is a whole number, keep one zero.
171  s.resize(p + (s[p] == '.' ? 2 : 1));
172  }
173  return s;
174 }
175 
176 template<> inline std::string NumToString<double>(double t) {
177  return FloatToString(t, 12);
178 }
179 template<> inline std::string NumToString<float>(float t) {
180  return FloatToString(t, 6);
181 }
182 
183 // Convert an integer value to a hexadecimal string.
184 // The returned string length is always xdigits long, prefixed by 0 digits.
185 // For example, IntToStringHex(0x23, 8) returns the string "00000023".
186 inline std::string IntToStringHex(int i, int xdigits) {
187  FLATBUFFERS_ASSERT(i >= 0);
188  // clang-format off
189 
190  #ifndef FLATBUFFERS_PREFER_PRINTF
191  std::stringstream ss;
192  ss << std::setw(xdigits) << std::setfill('0') << std::hex << std::uppercase
193  << i;
194  return ss.str();
195  #else // FLATBUFFERS_PREFER_PRINTF
196  return NumToStringImplWrapper(i, "%.*X", xdigits);
197  #endif // FLATBUFFERS_PREFER_PRINTF
198  // clang-format on
199 }
200 
201 // clang-format off
202 // Use locale independent functions {strtod_l, strtof_l, strtoll_l, strtoull_l}.
203 #if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
204  class ClassicLocale {
205  #ifdef _MSC_VER
206  typedef _locale_t locale_type;
207  #else
208  typedef locale_t locale_type; // POSIX.1-2008 locale_t type
209  #endif
210  ClassicLocale();
211  ~ClassicLocale();
212  locale_type locale_;
213  static ClassicLocale instance_;
214  public:
215  static locale_type Get() { return instance_.locale_; }
216  };
217 
218  #ifdef _MSC_VER
219  #define __strtoull_impl(s, pe, b) _strtoui64_l(s, pe, b, ClassicLocale::Get())
220  #define __strtoll_impl(s, pe, b) _strtoi64_l(s, pe, b, ClassicLocale::Get())
221  #define __strtod_impl(s, pe) _strtod_l(s, pe, ClassicLocale::Get())
222  #define __strtof_impl(s, pe) _strtof_l(s, pe, ClassicLocale::Get())
223  #else
224  #define __strtoull_impl(s, pe, b) strtoull_l(s, pe, b, ClassicLocale::Get())
225  #define __strtoll_impl(s, pe, b) strtoll_l(s, pe, b, ClassicLocale::Get())
226  #define __strtod_impl(s, pe) strtod_l(s, pe, ClassicLocale::Get())
227  #define __strtof_impl(s, pe) strtof_l(s, pe, ClassicLocale::Get())
228  #endif
229 #else
230  #define __strtod_impl(s, pe) strtod(s, pe)
231  #define __strtof_impl(s, pe) static_cast<float>(strtod(s, pe))
232  #ifdef _MSC_VER
233  #define __strtoull_impl(s, pe, b) _strtoui64(s, pe, b)
234  #define __strtoll_impl(s, pe, b) _strtoi64(s, pe, b)
235  #else
236  #define __strtoull_impl(s, pe, b) strtoull(s, pe, b)
237  #define __strtoll_impl(s, pe, b) strtoll(s, pe, b)
238  #endif
239 #endif
240 
241 inline void strtoval_impl(int64_t *val, const char *str, char **endptr,
242  int base) {
243  *val = __strtoll_impl(str, endptr, base);
244 }
245 
246 inline void strtoval_impl(uint64_t *val, const char *str, char **endptr,
247  int base) {
248  *val = __strtoull_impl(str, endptr, base);
249 }
250 
251 inline void strtoval_impl(double *val, const char *str, char **endptr) {
252  *val = __strtod_impl(str, endptr);
253 }
254 
255 // UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true.
256 __supress_ubsan__("float-cast-overflow")
257 inline void strtoval_impl(float *val, const char *str, char **endptr) {
258  *val = __strtof_impl(str, endptr);
259 }
260 #undef __strtoull_impl
261 #undef __strtoll_impl
262 #undef __strtod_impl
263 #undef __strtof_impl
264 // clang-format on
265 
266 // Adaptor for strtoull()/strtoll().
267 // Flatbuffers accepts numbers with any count of leading zeros (-009 is -9),
268 // while strtoll with base=0 interprets first leading zero as octal prefix.
269 // In future, it is possible to add prefixed 0b0101.
270 // 1) Checks errno code for overflow condition (out of range).
271 // 2) If base <= 0, function try to detect base of number by prefix.
272 //
273 // Return value (like strtoull and strtoll, but reject partial result):
274 // - If successful, an integer value corresponding to the str is returned.
275 // - If full string conversion can't be performed, 0 is returned.
276 // - If the converted value falls out of range of corresponding return type, a
277 // range error occurs. In this case value MAX(T)/MIN(T) is returned.
278 template<typename T>
279 inline bool StringToIntegerImpl(T *val, const char *const str,
280  const int base = 0,
281  const bool check_errno = true) {
282  // T is int64_t or uint64_T
283  FLATBUFFERS_ASSERT(str);
284  if (base <= 0) {
285  auto s = str;
286  while (*s && !is_digit(*s)) s++;
287  if (s[0] == '0' && is_alpha_char(s[1], 'X'))
288  return StringToIntegerImpl(val, str, 16, check_errno);
289  // if a prefix not match, try base=10
290  return StringToIntegerImpl(val, str, 10, check_errno);
291  } else {
292  if (check_errno) errno = 0; // clear thread-local errno
293  auto endptr = str;
294  strtoval_impl(val, str, const_cast<char **>(&endptr), base);
295  if ((*endptr != '\0') || (endptr == str)) {
296  *val = 0; // erase partial result
297  return false; // invalid string
298  }
299  // errno is out-of-range, return MAX/MIN
300  if (check_errno && errno) return false;
301  return true;
302  }
303 }
304 
305 template<typename T>
306 inline bool StringToFloatImpl(T *val, const char *const str) {
307  // Type T must be either float or double.
308  FLATBUFFERS_ASSERT(str && val);
309  auto end = str;
310  strtoval_impl(val, str, const_cast<char **>(&end));
311  auto done = (end != str) && (*end == '\0');
312  if (!done) *val = 0; // erase partial result
313  return done;
314 }
315 
316 // Convert a string to an instance of T.
317 // Return value (matched with StringToInteger64Impl and strtod):
318 // - If successful, a numeric value corresponding to the str is returned.
319 // - If full string conversion can't be performed, 0 is returned.
320 // - If the converted value falls out of range of corresponding return type, a
321 // range error occurs. In this case value MAX(T)/MIN(T) is returned.
322 template<typename T> inline bool StringToNumber(const char *s, T *val) {
323  FLATBUFFERS_ASSERT(s && val);
324  int64_t i64;
325  // The errno check isn't needed, will return MAX/MIN on overflow.
326  if (StringToIntegerImpl(&i64, s, 0, false)) {
327  const int64_t max = flatbuffers::numeric_limits<T>::max();
328  const int64_t min = flatbuffers::numeric_limits<T>::lowest();
329  if (i64 > max) {
330  *val = static_cast<T>(max);
331  return false;
332  }
333  if (i64 < min) {
334  // For unsigned types return max to distinguish from
335  // "no conversion can be performed" when 0 is returned.
336  *val = static_cast<T>(flatbuffers::is_unsigned<T>::value ? max : min);
337  return false;
338  }
339  *val = static_cast<T>(i64);
340  return true;
341  }
342  *val = 0;
343  return false;
344 }
345 
346 template<> inline bool StringToNumber<int64_t>(const char *str, int64_t *val) {
347  return StringToIntegerImpl(val, str);
348 }
349 
350 template<>
351 inline bool StringToNumber<uint64_t>(const char *str, uint64_t *val) {
352  if (!StringToIntegerImpl(val, str)) return false;
353  // The strtoull accepts negative numbers:
354  // If the minus sign was part of the input sequence, the numeric value
355  // calculated from the sequence of digits is negated as if by unary minus
356  // in the result type, which applies unsigned integer wraparound rules.
357  // Fix this behaviour (except -0).
358  if (*val) {
359  auto s = str;
360  while (*s && !is_digit(*s)) s++;
361  s = (s > str) ? (s - 1) : s; // step back to one symbol
362  if (*s == '-') {
363  // For unsigned types return the max to distinguish from
364  // "no conversion can be performed".
366  return false;
367  }
368  }
369  return true;
370 }
371 
372 template<> inline bool StringToNumber(const char *s, float *val) {
373  return StringToFloatImpl(val, s);
374 }
375 
376 template<> inline bool StringToNumber(const char *s, double *val) {
377  return StringToFloatImpl(val, s);
378 }
379 
380 inline int64_t StringToInt(const char *s, int base = 10) {
381  int64_t val;
382  return StringToIntegerImpl(&val, s, base) ? val : 0;
383 }
384 
385 inline uint64_t StringToUInt(const char *s, int base = 10) {
386  uint64_t val;
387  return StringToIntegerImpl(&val, s, base) ? val : 0;
388 }
389 
390 typedef bool (*LoadFileFunction)(const char *filename, bool binary,
391  std::string *dest);
392 typedef bool (*FileExistsFunction)(const char *filename);
393 
395 
397  FileExistsFunction file_exists_function);
398 
399 // Check if file "name" exists.
400 bool FileExists(const char *name);
401 
402 // Check if "name" exists and it is also a directory.
403 bool DirExists(const char *name);
404 
405 // Load file "name" into "buf" returning true if successful
406 // false otherwise. If "binary" is false data is read
407 // using ifstream's text mode, otherwise data is read with
408 // no transcoding.
409 bool LoadFile(const char *name, bool binary, std::string *buf);
410 
411 // Save data "buf" of length "len" bytes into a file
412 // "name" returning true if successful, false otherwise.
413 // If "binary" is false data is written using ifstream's
414 // text mode, otherwise data is written with no
415 // transcoding.
416 bool SaveFile(const char *name, const char *buf, size_t len, bool binary);
417 
418 // Save data "buf" into file "name" returning true if
419 // successful, false otherwise. If "binary" is false
420 // data is written using ifstream's text mode, otherwise
421 // data is written with no transcoding.
422 inline bool SaveFile(const char *name, const std::string &buf, bool binary) {
423  return SaveFile(name, buf.c_str(), buf.size(), binary);
424 }
425 
426 // Functionality for minimalistic portable path handling.
427 
428 // The functions below behave correctly regardless of whether posix ('/') or
429 // Windows ('/' or '\\') separators are used.
430 
431 // Any new separators inserted are always posix.
432 FLATBUFFERS_CONSTEXPR char kPathSeparator = '/';
433 
434 // Returns the path with the extension, if any, removed.
435 std::string StripExtension(const std::string &filepath);
436 
437 // Returns the extension, if any.
438 std::string GetExtension(const std::string &filepath);
439 
440 // Return the last component of the path, after the last separator.
441 std::string StripPath(const std::string &filepath);
442 
443 // Strip the last component of the path + separator.
444 std::string StripFileName(const std::string &filepath);
445 
446 // Concatenates a path with a filename, regardless of wether the path
447 // ends in a separator or not.
448 std::string ConCatPathFileName(const std::string &path,
449  const std::string &filename);
450 
451 // Replaces any '\\' separators with '/'
452 std::string PosixPath(const char *path);
453 
454 // This function ensure a directory exists, by recursively
455 // creating dirs for any parts of the path that don't exist yet.
456 void EnsureDirExists(const std::string &filepath);
457 
458 // Obtains the absolute path from any other path.
459 // Returns the input path if the absolute path couldn't be resolved.
460 std::string AbsolutePath(const std::string &filepath);
461 
462 // To and from UTF-8 unicode conversion functions
463 
464 // Convert a unicode code point into a UTF-8 representation by appending it
465 // to a string. Returns the number of bytes generated.
466 inline int ToUTF8(uint32_t ucc, std::string *out) {
467  FLATBUFFERS_ASSERT(!(ucc & 0x80000000)); // Top bit can't be set.
468  // 6 possible encodings: http://en.wikipedia.org/wiki/UTF-8
469  for (int i = 0; i < 6; i++) {
470  // Max bits this encoding can represent.
471  uint32_t max_bits = 6 + i * 5 + static_cast<int>(!i);
472  if (ucc < (1u << max_bits)) { // does it fit?
473  // Remaining bits not encoded in the first byte, store 6 bits each
474  uint32_t remain_bits = i * 6;
475  // Store first byte:
476  (*out) += static_cast<char>((0xFE << (max_bits - remain_bits)) |
477  (ucc >> remain_bits));
478  // Store remaining bytes:
479  for (int j = i - 1; j >= 0; j--) {
480  (*out) += static_cast<char>(((ucc >> (j * 6)) & 0x3F) | 0x80);
481  }
482  return i + 1; // Return the number of bytes added.
483  }
484  }
485  FLATBUFFERS_ASSERT(0); // Impossible to arrive here.
486  return -1;
487 }
488 
489 // Converts whatever prefix of the incoming string corresponds to a valid
490 // UTF-8 sequence into a unicode code. The incoming pointer will have been
491 // advanced past all bytes parsed.
492 // returns -1 upon corrupt UTF-8 encoding (ignore the incoming pointer in
493 // this case).
494 inline int FromUTF8(const char **in) {
495  int len = 0;
496  // Count leading 1 bits.
497  for (int mask = 0x80; mask >= 0x04; mask >>= 1) {
498  if (**in & mask) {
499  len++;
500  } else {
501  break;
502  }
503  }
504  if ((static_cast<unsigned char>(**in) << len) & 0x80)
505  return -1; // Bit after leading 1's must be 0.
506  if (!len) return *(*in)++;
507  // UTF-8 encoded values with a length are between 2 and 4 bytes.
508  if (len < 2 || len > 4) { return -1; }
509  // Grab initial bits of the code.
510  int ucc = *(*in)++ & ((1 << (7 - len)) - 1);
511  for (int i = 0; i < len - 1; i++) {
512  if ((**in & 0xC0) != 0x80) return -1; // Upper bits must 1 0.
513  ucc <<= 6;
514  ucc |= *(*in)++ & 0x3F; // Grab 6 more bits of the code.
515  }
516  // UTF-8 cannot encode values between 0xD800 and 0xDFFF (reserved for
517  // UTF-16 surrogate pairs).
518  if (ucc >= 0xD800 && ucc <= 0xDFFF) { return -1; }
519  // UTF-8 must represent code points in their shortest possible encoding.
520  switch (len) {
521  case 2:
522  // Two bytes of UTF-8 can represent code points from U+0080 to U+07FF.
523  if (ucc < 0x0080 || ucc > 0x07FF) { return -1; }
524  break;
525  case 3:
526  // Three bytes of UTF-8 can represent code points from U+0800 to U+FFFF.
527  if (ucc < 0x0800 || ucc > 0xFFFF) { return -1; }
528  break;
529  case 4:
530  // Four bytes of UTF-8 can represent code points from U+10000 to U+10FFFF.
531  if (ucc < 0x10000 || ucc > 0x10FFFF) { return -1; }
532  break;
533  }
534  return ucc;
535 }
536 
537 #ifndef FLATBUFFERS_PREFER_PRINTF
538 // Wraps a string to a maximum length, inserting new lines where necessary. Any
539 // existing whitespace will be collapsed down to a single space. A prefix or
540 // suffix can be provided, which will be inserted before or after a wrapped
541 // line, respectively.
542 inline std::string WordWrap(const std::string in, size_t max_length,
543  const std::string wrapped_line_prefix,
544  const std::string wrapped_line_suffix) {
545  std::istringstream in_stream(in);
546  std::string wrapped, line, word;
547 
548  in_stream >> word;
549  line = word;
550 
551  while (in_stream >> word) {
552  if ((line.length() + 1 + word.length() + wrapped_line_suffix.length()) <
553  max_length) {
554  line += " " + word;
555  } else {
556  wrapped += line + wrapped_line_suffix + "\n";
557  line = wrapped_line_prefix + word;
558  }
559  }
560  wrapped += line;
561 
562  return wrapped;
563 }
564 #endif // !FLATBUFFERS_PREFER_PRINTF
565 
566 inline bool EscapeString(const char *s, size_t length, std::string *_text,
567  bool allow_non_utf8, bool natural_utf8) {
568  std::string &text = *_text;
569  text += "\"";
570  for (uoffset_t i = 0; i < length; i++) {
571  char c = s[i];
572  switch (c) {
573  case '\n': text += "\\n"; break;
574  case '\t': text += "\\t"; break;
575  case '\r': text += "\\r"; break;
576  case '\b': text += "\\b"; break;
577  case '\f': text += "\\f"; break;
578  case '\"': text += "\\\""; break;
579  case '\\': text += "\\\\"; break;
580  default:
581  if (c >= ' ' && c <= '~') {
582  text += c;
583  } else {
584  // Not printable ASCII data. Let's see if it's valid UTF-8 first:
585  const char *utf8 = s + i;
586  int ucc = FromUTF8(&utf8);
587  if (ucc < 0) {
588  if (allow_non_utf8) {
589  text += "\\x";
590  text += IntToStringHex(static_cast<uint8_t>(c), 2);
591  } else {
592  // There are two cases here:
593  //
594  // 1) We reached here by parsing an IDL file. In that case,
595  // we previously checked for non-UTF-8, so we shouldn't reach
596  // here.
597  //
598  // 2) We reached here by someone calling GenerateText()
599  // on a previously-serialized flatbuffer. The data might have
600  // non-UTF-8 Strings, or might be corrupt.
601  //
602  // In both cases, we have to give up and inform the caller
603  // they have no JSON.
604  return false;
605  }
606  } else {
607  if (natural_utf8) {
608  // utf8 points to past all utf-8 bytes parsed
609  text.append(s + i, static_cast<size_t>(utf8 - s - i));
610  } else if (ucc <= 0xFFFF) {
611  // Parses as Unicode within JSON's \uXXXX range, so use that.
612  text += "\\u";
613  text += IntToStringHex(ucc, 4);
614  } else if (ucc <= 0x10FFFF) {
615  // Encode Unicode SMP values to a surrogate pair using two \u
616  // escapes.
617  uint32_t base = ucc - 0x10000;
618  auto high_surrogate = (base >> 10) + 0xD800;
619  auto low_surrogate = (base & 0x03FF) + 0xDC00;
620  text += "\\u";
621  text += IntToStringHex(high_surrogate, 4);
622  text += "\\u";
623  text += IntToStringHex(low_surrogate, 4);
624  }
625  // Skip past characters recognized.
626  i = static_cast<uoffset_t>(utf8 - s - 1);
627  }
628  }
629  break;
630  }
631  }
632  text += "\"";
633  return true;
634 }
635 
636 // Remove paired quotes in a string: "text"|'text' -> text.
637 std::string RemoveStringQuotes(const std::string &s);
638 
639 // Change th global C-locale to locale with name <locale_name>.
640 // Returns an actual locale name in <_value>, useful if locale_name is "" or
641 // null.
642 bool SetGlobalTestLocale(const char *locale_name,
643  std::string *_value = nullptr);
644 
645 // Read (or test) a value of environment variable.
646 bool ReadEnvironmentVariable(const char *var_name,
647  std::string *_value = nullptr);
648 
649 } // namespace flatbuffers
650 
651 #endif // FLATBUFFERS_UTIL_H_
bool ReadEnvironmentVariable(const char *var_name, std::string *_value=nullptr)
bool SetGlobalTestLocale(const char *locale_name, std::string *_value=nullptr)
std::string IntToStringHex(int i, int xdigits)
Definition: util.h:186
std::string AbsolutePath(const std::string &filepath)
bool(* FileExistsFunction)(const char *filename)
Definition: util.h:392
bool is_alpha(char c)
Definition: util.h:48
bool check_in_range(T x, T a, T b)
Definition: util.h:40
bool FileExists(const char *name)
#define FLATBUFFERS_ASSERT
bool DirExists(const char *name)
std::string NumToString< signed char >(signed char t)
Definition: util.h:127
void strtoval_impl(int64_t *val, const char *str, char **endptr, int base)
Definition: util.h:241
bool is_digit(char c)
Definition: util.h:65
bool LoadFile(const char *name, bool binary, std::string *buf)
bool(* LoadFileFunction)(const char *filename, bool binary, std::string *dest)
Definition: util.h:390
std::string GetExtension(const std::string &filepath)
bool StringToIntegerImpl(T *val, const char *const str, const int base=0, const bool check_errno=true)
Definition: util.h:279
bool EscapeString(const char *s, size_t length, std::string *_text, bool allow_non_utf8, bool natural_utf8)
Definition: util.h:566
bool is_alpha_char(char c, char alpha)
Definition: util.h:54
std::string ConCatPathFileName(const std::string &path, const std::string &filename)
std::string PosixPath(const char *path)
__supress_ubsan__("float-cast-overflow") inline void strtoval_impl(float *val
bool StringToNumber(const char *s, T *val)
Definition: util.h:322
FLATBUFFERS_CONSTEXPR char kPathSeparator
Definition: util.h:432
const char char ** endptr
Definition: util.h:257
std::string RemoveStringQuotes(const std::string &s)
#define __strtoull_impl(s, pe, b)
Definition: util.h:236
bool StringToFloatImpl(T *val, const char *const str)
Definition: util.h:306
LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function)
std::string WordWrap(const std::string in, size_t max_length, const std::string wrapped_line_prefix, const std::string wrapped_line_suffix)
Definition: util.h:542
void EnsureDirExists(const std::string &filepath)
#define __strtof_impl(s, pe)
Definition: util.h:231
const char * str
Definition: util.h:257
FileExistsFunction SetFileExistsFunction(FileExistsFunction file_exists_function)
Simple class for manipulating paths on Linux/Windows/Mac OS.
Definition: path.h:42
bool is_alnum(char c)
Definition: util.h:73
int FromUTF8(const char **in)
Definition: util.h:494
std::string NumToString(T t)
Definition: util.h:113
#define __strtoll_impl(s, pe, b)
Definition: util.h:237
std::string NumToString< unsigned char >(unsigned char t)
Definition: util.h:130
std::string NumToString< float >(float t)
Definition: util.h:179
std::string StripPath(const std::string &filepath)
int64_t StringToInt(const char *s, int base=10)
Definition: util.h:380
#define __strtod_impl(s, pe)
Definition: util.h:230
uint64_t StringToUInt(const char *s, int base=10)
Definition: util.h:385
bool StringToNumber< int64_t >(const char *str, int64_t *val)
Definition: util.h:346
bool is_xdigit(char c)
Definition: util.h:67
std::string FloatToString(T t, int precision)
Definition: util.h:149
bool StringToNumber< uint64_t >(const char *str, uint64_t *val)
Definition: util.h:351
std::string NumToString< double >(double t)
Definition: util.h:176
std::string StripExtension(const std::string &filepath)
std::string StripFileName(const std::string &filepath)
int ToUTF8(uint32_t ucc, std::string *out)
Definition: util.h:466
bool SaveFile(const char *name, const char *buf, size_t len, bool binary)


behaviortree_cpp
Author(s): Michele Colledanchise, Davide Faconti
autogenerated on Sat Jun 8 2019 18:04:05