Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-08-27 09:30:29

0001 /*
0002  * Copyright 2014 Google Inc. All rights reserved.
0003  *
0004  * Licensed under the Apache License, Version 2.0 (the "License");
0005  * you may not use this file except in compliance with the License.
0006  * You may obtain a copy of the License at
0007  *
0008  *     http://www.apache.org/licenses/LICENSE-2.0
0009  *
0010  * Unless required by applicable law or agreed to in writing, software
0011  * distributed under the License is distributed on an "AS IS" BASIS,
0012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0013  * See the License for the specific language governing permissions and
0014  * limitations under the License.
0015  */
0016 
0017 #ifndef FLATBUFFERS_UTIL_H_
0018 #define FLATBUFFERS_UTIL_H_
0019 
0020 #include <ctype.h>
0021 #include <errno.h>
0022 
0023 #include "flatbuffers/base.h"
0024 #include "flatbuffers/stl_emulation.h"
0025 
0026 #ifndef FLATBUFFERS_PREFER_PRINTF
0027 #  include <iomanip>
0028 #  include <sstream>
0029 #else  // FLATBUFFERS_PREFER_PRINTF
0030 #  include <float.h>
0031 #  include <stdio.h>
0032 #endif  // FLATBUFFERS_PREFER_PRINTF
0033 
0034 #include <cmath>
0035 #include <limits>
0036 #include <string>
0037 
0038 namespace flatbuffers {
0039 
0040 // @locale-independent functions for ASCII characters set.
0041 
0042 // Fast checking that character lies in closed range: [a <= x <= b]
0043 // using one compare (conditional branch) operator.
0044 inline bool check_ascii_range(char x, char a, char b) {
0045   FLATBUFFERS_ASSERT(a <= b);
0046   // (Hacker's Delight): `a <= x <= b` <=> `(x-a) <={u} (b-a)`.
0047   // The x, a, b will be promoted to int and subtracted without overflow.
0048   return static_cast<unsigned int>(x - a) <= static_cast<unsigned int>(b - a);
0049 }
0050 
0051 // Case-insensitive isalpha
0052 inline bool is_alpha(char c) {
0053   // ASCII only: alpha to upper case => reset bit 0x20 (~0x20 = 0xDF).
0054   return check_ascii_range(c & 0xDF, 'a' & 0xDF, 'z' & 0xDF);
0055 }
0056 
0057 // Check for uppercase alpha
0058 inline bool is_alpha_upper(char c) { return check_ascii_range(c, 'A', 'Z'); }
0059 
0060 // Check (case-insensitive) that `c` is equal to alpha.
0061 inline bool is_alpha_char(char c, char alpha) {
0062   FLATBUFFERS_ASSERT(is_alpha(alpha));
0063   // ASCII only: alpha to upper case => reset bit 0x20 (~0x20 = 0xDF).
0064   return ((c & 0xDF) == (alpha & 0xDF));
0065 }
0066 
0067 // https://en.cppreference.com/w/cpp/string/byte/isxdigit
0068 // isdigit and isxdigit are the only standard narrow character classification
0069 // functions that are not affected by the currently installed C locale. although
0070 // some implementations (e.g. Microsoft in 1252 codepage) may classify
0071 // additional single-byte characters as digits.
0072 inline bool is_digit(char c) { return check_ascii_range(c, '0', '9'); }
0073 
0074 inline bool is_xdigit(char c) {
0075   // Replace by look-up table.
0076   return is_digit(c) || check_ascii_range(c & 0xDF, 'a' & 0xDF, 'f' & 0xDF);
0077 }
0078 
0079 // Case-insensitive isalnum
0080 inline bool is_alnum(char c) { return is_alpha(c) || is_digit(c); }
0081 
0082 inline char CharToUpper(char c) {
0083   return static_cast<char>(::toupper(static_cast<unsigned char>(c)));
0084 }
0085 
0086 inline char CharToLower(char c) {
0087   return static_cast<char>(::tolower(static_cast<unsigned char>(c)));
0088 }
0089 
0090 // @end-locale-independent functions for ASCII character set
0091 
0092 #ifdef FLATBUFFERS_PREFER_PRINTF
0093 template<typename T> size_t IntToDigitCount(T t) {
0094   size_t digit_count = 0;
0095   // Count the sign for negative numbers
0096   if (t < 0) digit_count++;
0097   // Count a single 0 left of the dot for fractional numbers
0098   if (-1 < t && t < 1) digit_count++;
0099   // Count digits until fractional part
0100   T eps = std::numeric_limits<T>::epsilon();
0101   while (t <= (-1 + eps) || (1 - eps) <= t) {
0102     t /= 10;
0103     digit_count++;
0104   }
0105   return digit_count;
0106 }
0107 
0108 template<typename T> size_t NumToStringWidth(T t, int precision = 0) {
0109   size_t string_width = IntToDigitCount(t);
0110   // Count the dot for floating point numbers
0111   if (precision) string_width += (precision + 1);
0112   return string_width;
0113 }
0114 
0115 template<typename T>
0116 std::string NumToStringImplWrapper(T t, const char *fmt, int precision = 0) {
0117   size_t string_width = NumToStringWidth(t, precision);
0118   std::string s(string_width, 0x00);
0119   // Allow snprintf to use std::string trailing null to detect buffer overflow
0120   snprintf(const_cast<char *>(s.data()), (s.size() + 1), fmt, string_width, t);
0121   return s;
0122 }
0123 #endif  // FLATBUFFERS_PREFER_PRINTF
0124 
0125 // Convert an integer or floating point value to a string.
0126 // In contrast to std::stringstream, "char" values are
0127 // converted to a string of digits, and we don't use scientific notation.
0128 template<typename T> std::string NumToString(T t) {
0129   // clang-format off
0130 
0131   #ifndef FLATBUFFERS_PREFER_PRINTF
0132     std::stringstream ss;
0133     ss << t;
0134     return ss.str();
0135   #else // FLATBUFFERS_PREFER_PRINTF
0136     auto v = static_cast<long long>(t);
0137     return NumToStringImplWrapper(v, "%.*lld");
0138   #endif // FLATBUFFERS_PREFER_PRINTF
0139   // clang-format on
0140 }
0141 // Avoid char types used as character data.
0142 template<> inline std::string NumToString<signed char>(signed char t) {
0143   return NumToString(static_cast<int>(t));
0144 }
0145 template<> inline std::string NumToString<unsigned char>(unsigned char t) {
0146   return NumToString(static_cast<int>(t));
0147 }
0148 template<> inline std::string NumToString<char>(char t) {
0149   return NumToString(static_cast<int>(t));
0150 }
0151 
0152 // Special versions for floats/doubles.
0153 template<typename T> std::string FloatToString(T t, int precision) {
0154   // clang-format off
0155 
0156   #ifndef FLATBUFFERS_PREFER_PRINTF
0157     // to_string() prints different numbers of digits for floats depending on
0158     // platform and isn't available on Android, so we use stringstream
0159     std::stringstream ss;
0160     // Use std::fixed to suppress scientific notation.
0161     ss << std::fixed;
0162     // Default precision is 6, we want that to be higher for doubles.
0163     ss << std::setprecision(precision);
0164     ss << t;
0165     auto s = ss.str();
0166   #else // FLATBUFFERS_PREFER_PRINTF
0167     auto v = static_cast<double>(t);
0168     auto s = NumToStringImplWrapper(v, "%0.*f", precision);
0169   #endif // FLATBUFFERS_PREFER_PRINTF
0170   // clang-format on
0171   // Sadly, std::fixed turns "1" into "1.00000", so here we undo that.
0172   auto p = s.find_last_not_of('0');
0173   if (p != std::string::npos) {
0174     // Strip trailing zeroes. If it is a whole number, keep one zero.
0175     s.resize(p + (s[p] == '.' ? 2 : 1));
0176   }
0177   return s;
0178 }
0179 
0180 template<> inline std::string NumToString<double>(double t) {
0181   return FloatToString(t, 12);
0182 }
0183 template<> inline std::string NumToString<float>(float t) {
0184   return FloatToString(t, 6);
0185 }
0186 
0187 // Convert an integer value to a hexadecimal string.
0188 // The returned string length is always xdigits long, prefixed by 0 digits.
0189 // For example, IntToStringHex(0x23, 8) returns the string "00000023".
0190 inline std::string IntToStringHex(int i, int xdigits) {
0191   FLATBUFFERS_ASSERT(i >= 0);
0192   // clang-format off
0193 
0194   #ifndef FLATBUFFERS_PREFER_PRINTF
0195     std::stringstream ss;
0196     ss << std::setw(xdigits) << std::setfill('0') << std::hex << std::uppercase
0197        << i;
0198     return ss.str();
0199   #else // FLATBUFFERS_PREFER_PRINTF
0200     return NumToStringImplWrapper(i, "%.*X", xdigits);
0201   #endif // FLATBUFFERS_PREFER_PRINTF
0202   // clang-format on
0203 }
0204 
0205 // clang-format off
0206 // Use locale independent functions {strtod_l, strtof_l, strtoll_l, strtoull_l}.
0207 #if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
0208   class ClassicLocale {
0209     #ifdef _MSC_VER
0210       typedef _locale_t locale_type;
0211     #else
0212       typedef locale_t locale_type;  // POSIX.1-2008 locale_t type
0213     #endif
0214     ClassicLocale();
0215     ~ClassicLocale();
0216     locale_type locale_;
0217     static ClassicLocale instance_;
0218   public:
0219     static locale_type Get() { return instance_.locale_; }
0220   };
0221 
0222   #ifdef _MSC_VER
0223     #define __strtoull_impl(s, pe, b) _strtoui64_l(s, pe, b, ClassicLocale::Get())
0224     #define __strtoll_impl(s, pe, b) _strtoi64_l(s, pe, b, ClassicLocale::Get())
0225     #define __strtod_impl(s, pe) _strtod_l(s, pe, ClassicLocale::Get())
0226     #define __strtof_impl(s, pe) _strtof_l(s, pe, ClassicLocale::Get())
0227   #else
0228     #define __strtoull_impl(s, pe, b) strtoull_l(s, pe, b, ClassicLocale::Get())
0229     #define __strtoll_impl(s, pe, b) strtoll_l(s, pe, b, ClassicLocale::Get())
0230     #define __strtod_impl(s, pe) strtod_l(s, pe, ClassicLocale::Get())
0231     #define __strtof_impl(s, pe) strtof_l(s, pe, ClassicLocale::Get())
0232   #endif
0233 #else
0234   #define __strtod_impl(s, pe) strtod(s, pe)
0235   #define __strtof_impl(s, pe) static_cast<float>(strtod(s, pe))
0236   #ifdef _MSC_VER
0237     #define __strtoull_impl(s, pe, b) _strtoui64(s, pe, b)
0238     #define __strtoll_impl(s, pe, b) _strtoi64(s, pe, b)
0239   #else
0240     #define __strtoull_impl(s, pe, b) strtoull(s, pe, b)
0241     #define __strtoll_impl(s, pe, b) strtoll(s, pe, b)
0242   #endif
0243 #endif
0244 
0245 inline void strtoval_impl(int64_t *val, const char *str, char **endptr,
0246                                  int base) {
0247     *val = __strtoll_impl(str, endptr, base);
0248 }
0249 
0250 inline void strtoval_impl(uint64_t *val, const char *str, char **endptr,
0251                                  int base) {
0252   *val = __strtoull_impl(str, endptr, base);
0253 }
0254 
0255 inline void strtoval_impl(double *val, const char *str, char **endptr) {
0256   *val = __strtod_impl(str, endptr);
0257 }
0258 
0259 // UBSAN: double to float is safe if numeric_limits<float>::is_iec559 is true.
0260 FLATBUFFERS_SUPPRESS_UBSAN("float-cast-overflow")
0261 inline void strtoval_impl(float *val, const char *str, char **endptr) {
0262   *val = __strtof_impl(str, endptr);
0263 }
0264 #undef __strtoull_impl
0265 #undef __strtoll_impl
0266 #undef __strtod_impl
0267 #undef __strtof_impl
0268 // clang-format on
0269 
0270 // Adaptor for strtoull()/strtoll().
0271 // Flatbuffers accepts numbers with any count of leading zeros (-009 is -9),
0272 // while strtoll with base=0 interprets first leading zero as octal prefix.
0273 // In future, it is possible to add prefixed 0b0101.
0274 // 1) Checks errno code for overflow condition (out of range).
0275 // 2) If base <= 0, function try to detect base of number by prefix.
0276 //
0277 // Return value (like strtoull and strtoll, but reject partial result):
0278 // - If successful, an integer value corresponding to the str is returned.
0279 // - If full string conversion can't be performed, 0 is returned.
0280 // - If the converted value falls out of range of corresponding return type, a
0281 // range error occurs. In this case value MAX(T)/MIN(T) is returned.
0282 template<typename T>
0283 inline bool StringToIntegerImpl(T *val, const char *const str,
0284                                 const int base = 0,
0285                                 const bool check_errno = true) {
0286   // T is int64_t or uint64_T
0287   FLATBUFFERS_ASSERT(str);
0288   if (base <= 0) {
0289     auto s = str;
0290     while (*s && !is_digit(*s)) s++;
0291     if (s[0] == '0' && is_alpha_char(s[1], 'X'))
0292       return StringToIntegerImpl(val, str, 16, check_errno);
0293     // if a prefix not match, try base=10
0294     return StringToIntegerImpl(val, str, 10, check_errno);
0295   } else {
0296     if (check_errno) errno = 0;  // clear thread-local errno
0297     auto endptr = str;
0298     strtoval_impl(val, str, const_cast<char **>(&endptr), base);
0299     if ((*endptr != '\0') || (endptr == str)) {
0300       *val = 0;      // erase partial result
0301       return false;  // invalid string
0302     }
0303     // errno is out-of-range, return MAX/MIN
0304     if (check_errno && errno) return false;
0305     return true;
0306   }
0307 }
0308 
0309 template<typename T>
0310 inline bool StringToFloatImpl(T *val, const char *const str) {
0311   // Type T must be either float or double.
0312   FLATBUFFERS_ASSERT(str && val);
0313   auto end = str;
0314   strtoval_impl(val, str, const_cast<char **>(&end));
0315   auto done = (end != str) && (*end == '\0');
0316   if (!done) *val = 0;  // erase partial result
0317   if (done && std::isnan(*val)) { *val = std::numeric_limits<T>::quiet_NaN(); }
0318   return done;
0319 }
0320 
0321 // Convert a string to an instance of T.
0322 // Return value (matched with StringToInteger64Impl and strtod):
0323 // - If successful, a numeric value corresponding to the str is returned.
0324 // - If full string conversion can't be performed, 0 is returned.
0325 // - If the converted value falls out of range of corresponding return type, a
0326 // range error occurs. In this case value MAX(T)/MIN(T) is returned.
0327 template<typename T> inline bool StringToNumber(const char *s, T *val) {
0328   // Assert on `unsigned long` and `signed long` on LP64.
0329   // If it is necessary, it could be solved with flatbuffers::enable_if<B,T>.
0330   static_assert(sizeof(T) < sizeof(int64_t), "unexpected type T");
0331   FLATBUFFERS_ASSERT(s && val);
0332   int64_t i64;
0333   // The errno check isn't needed, will return MAX/MIN on overflow.
0334   if (StringToIntegerImpl(&i64, s, 0, false)) {
0335     const int64_t max = (flatbuffers::numeric_limits<T>::max)();
0336     const int64_t min = flatbuffers::numeric_limits<T>::lowest();
0337     if (i64 > max) {
0338       *val = static_cast<T>(max);
0339       return false;
0340     }
0341     if (i64 < min) {
0342       // For unsigned types return max to distinguish from
0343       // "no conversion can be performed" when 0 is returned.
0344       *val = static_cast<T>(flatbuffers::is_unsigned<T>::value ? max : min);
0345       return false;
0346     }
0347     *val = static_cast<T>(i64);
0348     return true;
0349   }
0350   *val = 0;
0351   return false;
0352 }
0353 
0354 template<> inline bool StringToNumber<int64_t>(const char *str, int64_t *val) {
0355   return StringToIntegerImpl(val, str);
0356 }
0357 
0358 template<>
0359 inline bool StringToNumber<uint64_t>(const char *str, uint64_t *val) {
0360   if (!StringToIntegerImpl(val, str)) return false;
0361   // The strtoull accepts negative numbers:
0362   // If the minus sign was part of the input sequence, the numeric value
0363   // calculated from the sequence of digits is negated as if by unary minus
0364   // in the result type, which applies unsigned integer wraparound rules.
0365   // Fix this behaviour (except -0).
0366   if (*val) {
0367     auto s = str;
0368     while (*s && !is_digit(*s)) s++;
0369     s = (s > str) ? (s - 1) : s;  // step back to one symbol
0370     if (*s == '-') {
0371       // For unsigned types return the max to distinguish from
0372       // "no conversion can be performed".
0373       *val = (flatbuffers::numeric_limits<uint64_t>::max)();
0374       return false;
0375     }
0376   }
0377   return true;
0378 }
0379 
0380 template<> inline bool StringToNumber(const char *s, float *val) {
0381   return StringToFloatImpl(val, s);
0382 }
0383 
0384 template<> inline bool StringToNumber(const char *s, double *val) {
0385   return StringToFloatImpl(val, s);
0386 }
0387 
0388 inline int64_t StringToInt(const char *s, int base = 10) {
0389   int64_t val;
0390   return StringToIntegerImpl(&val, s, base) ? val : 0;
0391 }
0392 
0393 inline uint64_t StringToUInt(const char *s, int base = 10) {
0394   uint64_t val;
0395   return StringToIntegerImpl(&val, s, base) ? val : 0;
0396 }
0397 
0398 inline bool StringIsFlatbufferNan(const std::string &s) {
0399   return s == "nan" || s == "+nan" || s == "-nan";
0400 }
0401 
0402 inline bool StringIsFlatbufferPositiveInfinity(const std::string &s) {
0403   return s == "inf" || s == "+inf" || s == "infinity" || s == "+infinity";
0404 }
0405 
0406 inline bool StringIsFlatbufferNegativeInfinity(const std::string &s) {
0407   return s == "-inf" || s == "-infinity";
0408 }
0409 
0410 typedef bool (*LoadFileFunction)(const char *filename, bool binary,
0411                                  std::string *dest);
0412 typedef bool (*FileExistsFunction)(const char *filename);
0413 
0414 LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function);
0415 
0416 FileExistsFunction SetFileExistsFunction(
0417     FileExistsFunction file_exists_function);
0418 
0419 // Check if file "name" exists.
0420 bool FileExists(const char *name);
0421 
0422 // Check if "name" exists and it is also a directory.
0423 bool DirExists(const char *name);
0424 
0425 // Load file "name" into "buf" returning true if successful
0426 // false otherwise.  If "binary" is false data is read
0427 // using ifstream's text mode, otherwise data is read with
0428 // no transcoding.
0429 bool LoadFile(const char *name, bool binary, std::string *buf);
0430 
0431 // Save data "buf" of length "len" bytes into a file
0432 // "name" returning true if successful, false otherwise.
0433 // If "binary" is false data is written using ifstream's
0434 // text mode, otherwise data is written with no
0435 // transcoding.
0436 bool SaveFile(const char *name, const char *buf, size_t len, bool binary);
0437 
0438 // Save data "buf" into file "name" returning true if
0439 // successful, false otherwise.  If "binary" is false
0440 // data is written using ifstream's text mode, otherwise
0441 // data is written with no transcoding.
0442 inline bool SaveFile(const char *name, const std::string &buf, bool binary) {
0443   return SaveFile(name, buf.c_str(), buf.size(), binary);
0444 }
0445 
0446 // Functionality for minimalistic portable path handling.
0447 
0448 // The functions below behave correctly regardless of whether posix ('/') or
0449 // Windows ('/' or '\\') separators are used.
0450 
0451 // Any new separators inserted are always posix.
0452 FLATBUFFERS_CONSTEXPR char kPathSeparator = '/';
0453 
0454 // Returns the path with the extension, if any, removed.
0455 std::string StripExtension(const std::string &filepath);
0456 
0457 // Returns the extension, if any.
0458 std::string GetExtension(const std::string &filepath);
0459 
0460 // Return the last component of the path, after the last separator.
0461 std::string StripPath(const std::string &filepath);
0462 
0463 // Strip the last component of the path + separator.
0464 std::string StripFileName(const std::string &filepath);
0465 
0466 std::string StripPrefix(const std::string &filepath,
0467                         const std::string &prefix_to_remove);
0468 
0469 // Concatenates a path with a filename, regardless of whether the path
0470 // ends in a separator or not.
0471 std::string ConCatPathFileName(const std::string &path,
0472                                const std::string &filename);
0473 
0474 // Replaces any '\\' separators with '/'
0475 std::string PosixPath(const char *path);
0476 std::string PosixPath(const std::string &path);
0477 
0478 // This function ensure a directory exists, by recursively
0479 // creating dirs for any parts of the path that don't exist yet.
0480 void EnsureDirExists(const std::string &filepath);
0481 
0482 // Obtains the relative or absolute path.
0483 std::string FilePath(const std::string &project,
0484                      const std::string &filePath,
0485                      bool absolute);
0486 
0487 // Obtains the absolute path from any other path.
0488 // Returns the input path if the absolute path couldn't be resolved.
0489 std::string AbsolutePath(const std::string &filepath);
0490 
0491 // Returns files relative to the --project_root path, prefixed with `//`.
0492 std::string RelativeToRootPath(const std::string &project,
0493                                const std::string &filepath);
0494 
0495 // To and from UTF-8 unicode conversion functions
0496 
0497 // Convert a unicode code point into a UTF-8 representation by appending it
0498 // to a string. Returns the number of bytes generated.
0499 inline int ToUTF8(uint32_t ucc, std::string *out) {
0500   FLATBUFFERS_ASSERT(!(ucc & 0x80000000));  // Top bit can't be set.
0501   // 6 possible encodings: http://en.wikipedia.org/wiki/UTF-8
0502   for (int i = 0; i < 6; i++) {
0503     // Max bits this encoding can represent.
0504     uint32_t max_bits = 6 + i * 5 + static_cast<int>(!i);
0505     if (ucc < (1u << max_bits)) {  // does it fit?
0506       // Remaining bits not encoded in the first byte, store 6 bits each
0507       uint32_t remain_bits = i * 6;
0508       // Store first byte:
0509       (*out) += static_cast<char>((0xFE << (max_bits - remain_bits)) |
0510                                   (ucc >> remain_bits));
0511       // Store remaining bytes:
0512       for (int j = i - 1; j >= 0; j--) {
0513         (*out) += static_cast<char>(((ucc >> (j * 6)) & 0x3F) | 0x80);
0514       }
0515       return i + 1;  // Return the number of bytes added.
0516     }
0517   }
0518   FLATBUFFERS_ASSERT(0);  // Impossible to arrive here.
0519   return -1;
0520 }
0521 
0522 // Converts whatever prefix of the incoming string corresponds to a valid
0523 // UTF-8 sequence into a unicode code. The incoming pointer will have been
0524 // advanced past all bytes parsed.
0525 // returns -1 upon corrupt UTF-8 encoding (ignore the incoming pointer in
0526 // this case).
0527 inline int FromUTF8(const char **in) {
0528   int len = 0;
0529   // Count leading 1 bits.
0530   for (int mask = 0x80; mask >= 0x04; mask >>= 1) {
0531     if (**in & mask) {
0532       len++;
0533     } else {
0534       break;
0535     }
0536   }
0537   if ((static_cast<unsigned char>(**in) << len) & 0x80)
0538     return -1;  // Bit after leading 1's must be 0.
0539   if (!len) return *(*in)++;
0540   // UTF-8 encoded values with a length are between 2 and 4 bytes.
0541   if (len < 2 || len > 4) { return -1; }
0542   // Grab initial bits of the code.
0543   int ucc = *(*in)++ & ((1 << (7 - len)) - 1);
0544   for (int i = 0; i < len - 1; i++) {
0545     if ((**in & 0xC0) != 0x80) return -1;  // Upper bits must 1 0.
0546     ucc <<= 6;
0547     ucc |= *(*in)++ & 0x3F;  // Grab 6 more bits of the code.
0548   }
0549   // UTF-8 cannot encode values between 0xD800 and 0xDFFF (reserved for
0550   // UTF-16 surrogate pairs).
0551   if (ucc >= 0xD800 && ucc <= 0xDFFF) { return -1; }
0552   // UTF-8 must represent code points in their shortest possible encoding.
0553   switch (len) {
0554     case 2:
0555       // Two bytes of UTF-8 can represent code points from U+0080 to U+07FF.
0556       if (ucc < 0x0080 || ucc > 0x07FF) { return -1; }
0557       break;
0558     case 3:
0559       // Three bytes of UTF-8 can represent code points from U+0800 to U+FFFF.
0560       if (ucc < 0x0800 || ucc > 0xFFFF) { return -1; }
0561       break;
0562     case 4:
0563       // Four bytes of UTF-8 can represent code points from U+10000 to U+10FFFF.
0564       if (ucc < 0x10000 || ucc > 0x10FFFF) { return -1; }
0565       break;
0566   }
0567   return ucc;
0568 }
0569 
0570 #ifndef FLATBUFFERS_PREFER_PRINTF
0571 // Wraps a string to a maximum length, inserting new lines where necessary. Any
0572 // existing whitespace will be collapsed down to a single space. A prefix or
0573 // suffix can be provided, which will be inserted before or after a wrapped
0574 // line, respectively.
0575 inline std::string WordWrap(const std::string in, size_t max_length,
0576                             const std::string wrapped_line_prefix,
0577                             const std::string wrapped_line_suffix) {
0578   std::istringstream in_stream(in);
0579   std::string wrapped, line, word;
0580 
0581   in_stream >> word;
0582   line = word;
0583 
0584   while (in_stream >> word) {
0585     if ((line.length() + 1 + word.length() + wrapped_line_suffix.length()) <
0586         max_length) {
0587       line += " " + word;
0588     } else {
0589       wrapped += line + wrapped_line_suffix + "\n";
0590       line = wrapped_line_prefix + word;
0591     }
0592   }
0593   wrapped += line;
0594 
0595   return wrapped;
0596 }
0597 #endif  // !FLATBUFFERS_PREFER_PRINTF
0598 
0599 inline bool EscapeString(const char *s, size_t length, std::string *_text,
0600                          bool allow_non_utf8, bool natural_utf8) {
0601   std::string &text = *_text;
0602   text += "\"";
0603   for (uoffset_t i = 0; i < length; i++) {
0604     char c = s[i];
0605     switch (c) {
0606       case '\n': text += "\\n"; break;
0607       case '\t': text += "\\t"; break;
0608       case '\r': text += "\\r"; break;
0609       case '\b': text += "\\b"; break;
0610       case '\f': text += "\\f"; break;
0611       case '\"': text += "\\\""; break;
0612       case '\\': text += "\\\\"; break;
0613       default:
0614         if (c >= ' ' && c <= '~') {
0615           text += c;
0616         } else {
0617           // Not printable ASCII data. Let's see if it's valid UTF-8 first:
0618           const char *utf8 = s + i;
0619           int ucc = FromUTF8(&utf8);
0620           if (ucc < 0) {
0621             if (allow_non_utf8) {
0622               text += "\\x";
0623               text += IntToStringHex(static_cast<uint8_t>(c), 2);
0624             } else {
0625               // There are two cases here:
0626               //
0627               // 1) We reached here by parsing an IDL file. In that case,
0628               // we previously checked for non-UTF-8, so we shouldn't reach
0629               // here.
0630               //
0631               // 2) We reached here by someone calling GenText()
0632               // on a previously-serialized flatbuffer. The data might have
0633               // non-UTF-8 Strings, or might be corrupt.
0634               //
0635               // In both cases, we have to give up and inform the caller
0636               // they have no JSON.
0637               return false;
0638             }
0639           } else {
0640             if (natural_utf8) {
0641               // utf8 points to past all utf-8 bytes parsed
0642               text.append(s + i, static_cast<size_t>(utf8 - s - i));
0643             } else if (ucc <= 0xFFFF) {
0644               // Parses as Unicode within JSON's \uXXXX range, so use that.
0645               text += "\\u";
0646               text += IntToStringHex(ucc, 4);
0647             } else if (ucc <= 0x10FFFF) {
0648               // Encode Unicode SMP values to a surrogate pair using two \u
0649               // escapes.
0650               uint32_t base = ucc - 0x10000;
0651               auto high_surrogate = (base >> 10) + 0xD800;
0652               auto low_surrogate = (base & 0x03FF) + 0xDC00;
0653               text += "\\u";
0654               text += IntToStringHex(high_surrogate, 4);
0655               text += "\\u";
0656               text += IntToStringHex(low_surrogate, 4);
0657             }
0658             // Skip past characters recognized.
0659             i = static_cast<uoffset_t>(utf8 - s - 1);
0660           }
0661         }
0662         break;
0663     }
0664   }
0665   text += "\"";
0666   return true;
0667 }
0668 
0669 inline std::string BufferToHexText(const void *buffer, size_t buffer_size,
0670                                    size_t max_length,
0671                                    const std::string &wrapped_line_prefix,
0672                                    const std::string &wrapped_line_suffix) {
0673   std::string text = wrapped_line_prefix;
0674   size_t start_offset = 0;
0675   const char *s = reinterpret_cast<const char *>(buffer);
0676   for (size_t i = 0; s && i < buffer_size; i++) {
0677     // Last iteration or do we have more?
0678     bool have_more = i + 1 < buffer_size;
0679     text += "0x";
0680     text += IntToStringHex(static_cast<uint8_t>(s[i]), 2);
0681     if (have_more) { text += ','; }
0682     // If we have more to process and we reached max_length
0683     if (have_more &&
0684         text.size() + wrapped_line_suffix.size() >= start_offset + max_length) {
0685       text += wrapped_line_suffix;
0686       text += '\n';
0687       start_offset = text.size();
0688       text += wrapped_line_prefix;
0689     }
0690   }
0691   text += wrapped_line_suffix;
0692   return text;
0693 }
0694 
0695 // Remove paired quotes in a string: "text"|'text' -> text.
0696 std::string RemoveStringQuotes(const std::string &s);
0697 
0698 // Change th global C-locale to locale with name <locale_name>.
0699 // Returns an actual locale name in <_value>, useful if locale_name is "" or
0700 // null.
0701 bool SetGlobalTestLocale(const char *locale_name,
0702                          std::string *_value = nullptr);
0703 
0704 // Read (or test) a value of environment variable.
0705 bool ReadEnvironmentVariable(const char *var_name,
0706                              std::string *_value = nullptr);
0707 
0708 enum class Case {
0709   kUnknown = 0,
0710   // TheQuickBrownFox
0711   kUpperCamel = 1,
0712   // theQuickBrownFox
0713   kLowerCamel = 2,
0714   // the_quick_brown_fox
0715   kSnake = 3,
0716   // THE_QUICK_BROWN_FOX
0717   kScreamingSnake = 4,
0718   // THEQUICKBROWNFOX
0719   kAllUpper = 5,
0720   // thequickbrownfox
0721   kAllLower = 6,
0722   // the-quick-brown-fox
0723   kDasher = 7,
0724   // THEQuiCKBr_ownFox (or whatever you want, we won't change it)
0725   kKeep = 8,
0726   // the_quick_brown_fox123 (as opposed to the_quick_brown_fox_123)
0727   kSnake2 = 9,
0728 };
0729 
0730 // Convert the `input` string of case `input_case` to the specified
0731 // `output_case`.
0732 std::string ConvertCase(const std::string &input, Case output_case,
0733                         Case input_case = Case::kSnake);
0734 
0735 }  // namespace flatbuffers
0736 
0737 #endif  // FLATBUFFERS_UTIL_H_