util.h 25 KB

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