util.h 24 KB

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