/src/flatbuffers/src/util.cpp
Line | Count | Source |
1 | | /* |
2 | | * Copyright 2016 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 | | // clang-format off |
18 | | // Dont't remove `format off`, it prevent reordering of win-includes. |
19 | | |
20 | | #include <cstring> |
21 | | #if defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__) || \ |
22 | | defined(__QNXNTO__) |
23 | | # define _POSIX_C_SOURCE 200809L |
24 | | # define _XOPEN_SOURCE 700L |
25 | | #endif |
26 | | |
27 | | #if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__) |
28 | | # ifndef WIN32_LEAN_AND_MEAN |
29 | | # define WIN32_LEAN_AND_MEAN |
30 | | # endif |
31 | | # ifndef NOMINMAX |
32 | | # define NOMINMAX |
33 | | # endif |
34 | | # ifdef _MSC_VER |
35 | | # include <crtdbg.h> |
36 | | # endif |
37 | | # include <windows.h> // Must be included before <direct.h> |
38 | | # ifndef __CYGWIN__ |
39 | | # include <direct.h> |
40 | | # endif |
41 | | # include <winbase.h> |
42 | | # undef interface // This is also important because of reasons |
43 | | #endif |
44 | | // clang-format on |
45 | | |
46 | | #include "flatbuffers/util.h" |
47 | | |
48 | | #include <sys/stat.h> |
49 | | |
50 | | #include <clocale> |
51 | | #include <cstdlib> |
52 | | #include <fstream> |
53 | | #include <functional> |
54 | | |
55 | | #include "flatbuffers/base.h" |
56 | | |
57 | | namespace flatbuffers { |
58 | | |
59 | | namespace { |
60 | | |
61 | 0 | static bool FileExistsRaw(const char* name) { |
62 | 0 | std::ifstream ifs(name); |
63 | 0 | return ifs.good(); |
64 | 0 | } |
65 | | |
66 | 2 | static bool LoadFileRaw(const char* name, bool binary, std::string* buf) { |
67 | 2 | if (DirExists(name)) return false; |
68 | 2 | std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in); |
69 | 2 | if (!ifs.is_open()) return false; |
70 | 2 | if (binary) { |
71 | | // The fastest way to read a file into a string. |
72 | 2 | ifs.seekg(0, std::ios::end); |
73 | 2 | auto size = ifs.tellg(); |
74 | 2 | (*buf).resize(static_cast<size_t>(size)); |
75 | 2 | ifs.seekg(0, std::ios::beg); |
76 | 2 | ifs.read(&(*buf)[0], (*buf).size()); |
77 | 2 | } else { |
78 | | // This is slower, but works correctly on all platforms for text files. |
79 | 0 | std::ostringstream oss; |
80 | 0 | oss << ifs.rdbuf(); |
81 | 0 | *buf = oss.str(); |
82 | 0 | } |
83 | 2 | return !ifs.bad(); |
84 | 2 | } |
85 | | |
86 | | LoadFileFunction g_load_file_function = LoadFileRaw; |
87 | | FileExistsFunction g_file_exists_function = FileExistsRaw; |
88 | | |
89 | 0 | static std::string ToCamelCase(const std::string& input, bool is_upper) { |
90 | 0 | std::string s; |
91 | 0 | for (size_t i = 0; i < input.length(); i++) { |
92 | 0 | if (!i && input[i] == '_') { |
93 | 0 | s += input[i]; |
94 | | // we ignore leading underscore but make following |
95 | | // alphabet char upper. |
96 | 0 | if (i + 1 < input.length() && is_alpha(input[i + 1])) |
97 | 0 | s += CharToUpper(input[++i]); |
98 | 0 | } else if (!i) |
99 | 0 | s += is_upper ? CharToUpper(input[i]) : CharToLower(input[i]); |
100 | 0 | else if (input[i] == '_' && i + 1 < input.length()) |
101 | 0 | s += CharToUpper(input[++i]); |
102 | 0 | else |
103 | 0 | s += input[i]; |
104 | 0 | } |
105 | 0 | return s; |
106 | 0 | } |
107 | | |
108 | 0 | static std::string ToSnakeCase(const std::string& input, bool screaming) { |
109 | 0 | std::string s; |
110 | 0 | for (size_t i = 0; i < input.length(); i++) { |
111 | 0 | if (i == 0) { |
112 | 0 | s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]); |
113 | 0 | } else if (input[i] == '_') { |
114 | 0 | s += '_'; |
115 | 0 | } else if (!islower(input[i])) { |
116 | | // Prevent duplicate underscores for Upper_Snake_Case strings |
117 | | // and UPPERCASE strings. |
118 | 0 | if (islower(input[i - 1]) || |
119 | 0 | (isdigit(input[i - 1]) && !isdigit(input[i]))) { |
120 | 0 | s += '_'; |
121 | 0 | } |
122 | 0 | s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]); |
123 | 0 | } else { |
124 | 0 | s += screaming ? CharToUpper(input[i]) : input[i]; |
125 | 0 | } |
126 | 0 | } |
127 | 0 | return s; |
128 | 0 | } |
129 | | |
130 | | std::string ToAll(const std::string& input, |
131 | 0 | std::function<char(const char)> transform) { |
132 | 0 | std::string s; |
133 | 0 | for (size_t i = 0; i < input.length(); i++) { |
134 | 0 | s += transform(input[i]); |
135 | 0 | } |
136 | 0 | return s; |
137 | 0 | } |
138 | | |
139 | 0 | std::string CamelToSnake(const std::string& input) { |
140 | 0 | std::string s; |
141 | 0 | for (size_t i = 0; i < input.length(); i++) { |
142 | 0 | if (i == 0) { |
143 | 0 | s += CharToLower(input[i]); |
144 | 0 | } else if (input[i] == '_') { |
145 | 0 | s += '_'; |
146 | 0 | } else if (!islower(input[i])) { |
147 | | // Prevent duplicate underscores for Upper_Snake_Case strings |
148 | | // and UPPERCASE strings. |
149 | 0 | if (islower(input[i - 1]) || |
150 | 0 | (isdigit(input[i - 1]) && !isdigit(input[i]))) { |
151 | 0 | s += '_'; |
152 | 0 | } |
153 | 0 | s += CharToLower(input[i]); |
154 | 0 | } else { |
155 | 0 | s += input[i]; |
156 | 0 | } |
157 | 0 | } |
158 | 0 | return s; |
159 | 0 | } |
160 | | |
161 | 0 | std::string DasherToSnake(const std::string& input) { |
162 | 0 | std::string s; |
163 | 0 | for (size_t i = 0; i < input.length(); i++) { |
164 | 0 | if (input[i] == '-') { |
165 | 0 | s += "_"; |
166 | 0 | } else { |
167 | 0 | s += input[i]; |
168 | 0 | } |
169 | 0 | } |
170 | 0 | return s; |
171 | 0 | } |
172 | | |
173 | 0 | std::string ToDasher(const std::string& input) { |
174 | 0 | std::string s; |
175 | 0 | char p = 0; |
176 | 0 | for (size_t i = 0; i < input.length(); i++) { |
177 | 0 | char const& c = input[i]; |
178 | 0 | if (c == '_') { |
179 | 0 | if (i > 0 && p != kPathSeparator && |
180 | | // The following is a special case to ignore digits after a _. This is |
181 | | // because ThisExample3 would be converted to this_example_3 in the |
182 | | // CamelToSnake conversion, and then dasher would do this-example-3, |
183 | | // but it expects this-example3. |
184 | 0 | !(i + 1 < input.length() && isdigit(input[i + 1]))) |
185 | 0 | s += "-"; |
186 | 0 | } else { |
187 | 0 | s += c; |
188 | 0 | } |
189 | 0 | p = c; |
190 | 0 | } |
191 | 0 | return s; |
192 | 0 | } |
193 | | |
194 | | // Converts foo_bar_123baz_456 to foo_bar123_baz456 |
195 | 0 | std::string SnakeToSnake2(const std::string& s) { |
196 | 0 | if (s.length() <= 1) return s; |
197 | 0 | std::string result; |
198 | 0 | result.reserve(s.size()); |
199 | 0 | for (size_t i = 0; i < s.length() - 1; i++) { |
200 | 0 | if (s[i] == '_' && isdigit(s[i + 1])) { |
201 | 0 | continue; // Move the `_` until after the digits. |
202 | 0 | } |
203 | | |
204 | 0 | result.push_back(s[i]); |
205 | |
|
206 | 0 | if (isdigit(s[i]) && isalpha(s[i + 1]) && islower(s[i + 1])) { |
207 | 0 | result.push_back('_'); |
208 | 0 | } |
209 | 0 | } |
210 | 0 | result.push_back(s.back()); |
211 | |
|
212 | 0 | return result; |
213 | 0 | } |
214 | | |
215 | | } // namespace |
216 | | |
217 | 2 | bool LoadFile(const char* name, bool binary, std::string* buf) { |
218 | 2 | FLATBUFFERS_ASSERT(g_load_file_function); |
219 | 2 | return g_load_file_function(name, binary, buf); |
220 | 2 | } |
221 | | |
222 | 0 | bool FileExists(const char* name) { |
223 | 0 | FLATBUFFERS_ASSERT(g_file_exists_function); |
224 | 0 | return g_file_exists_function(name); |
225 | 0 | } |
226 | | |
227 | 2 | bool DirExists(const char* name) { |
228 | | // clang-format off |
229 | | |
230 | | #ifdef _WIN32 |
231 | | #define flatbuffers_stat _stat |
232 | | #define FLATBUFFERS_S_IFDIR _S_IFDIR |
233 | | #else |
234 | 2 | #define flatbuffers_stat stat |
235 | 2 | #define FLATBUFFERS_S_IFDIR S_IFDIR |
236 | 2 | #endif |
237 | | // clang-format on |
238 | 2 | struct flatbuffers_stat file_info; |
239 | 2 | if (flatbuffers_stat(name, &file_info) != 0) return false; |
240 | 2 | return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0; |
241 | 2 | } |
242 | | |
243 | 0 | LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) { |
244 | 0 | LoadFileFunction previous_function = g_load_file_function; |
245 | 0 | g_load_file_function = load_file_function ? load_file_function : LoadFileRaw; |
246 | 0 | return previous_function; |
247 | 0 | } |
248 | | |
249 | | FileExistsFunction SetFileExistsFunction( |
250 | 0 | FileExistsFunction file_exists_function) { |
251 | 0 | FileExistsFunction previous_function = g_file_exists_function; |
252 | 0 | g_file_exists_function = |
253 | 0 | file_exists_function ? file_exists_function : FileExistsRaw; |
254 | 0 | return previous_function; |
255 | 0 | } |
256 | | |
257 | 0 | bool SaveFile(const char* name, const char* buf, size_t len, bool binary) { |
258 | 0 | std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out); |
259 | 0 | if (!ofs.is_open()) return false; |
260 | 0 | ofs.write(buf, len); |
261 | 0 | return !ofs.bad(); |
262 | 0 | } |
263 | | |
264 | | // We internally store paths in posix format ('/'). Paths supplied |
265 | | // by the user should go through PosixPath to ensure correct behavior |
266 | | // on Windows when paths are string-compared. |
267 | | |
268 | | static const char kPathSeparatorWindows = '\\'; |
269 | | static const char* PathSeparatorSet = "\\/"; // Intentionally no ':' |
270 | | |
271 | 0 | std::string StripExtension(const std::string& filepath) { |
272 | 0 | size_t i = filepath.find_last_of('.'); |
273 | 0 | return i != std::string::npos ? filepath.substr(0, i) : filepath; |
274 | 0 | } |
275 | | |
276 | 0 | std::string GetExtension(const std::string& filepath) { |
277 | 0 | size_t i = filepath.find_last_of('.'); |
278 | 0 | return i != std::string::npos ? filepath.substr(i + 1) : ""; |
279 | 0 | } |
280 | | |
281 | 0 | std::string StripPath(const std::string& filepath) { |
282 | 0 | size_t i = filepath.find_last_of(PathSeparatorSet); |
283 | 0 | return i != std::string::npos ? filepath.substr(i + 1) : filepath; |
284 | 0 | } |
285 | | |
286 | 0 | std::string StripFileName(const std::string& filepath) { |
287 | 0 | size_t i = filepath.find_last_of(PathSeparatorSet); |
288 | 0 | return i != std::string::npos ? filepath.substr(0, i) : ""; |
289 | 0 | } |
290 | | |
291 | | std::string StripPrefix(const std::string& filepath, |
292 | 0 | const std::string& prefix_to_remove) { |
293 | 0 | if (!strncmp(filepath.c_str(), prefix_to_remove.c_str(), |
294 | 0 | prefix_to_remove.size())) { |
295 | 0 | return filepath.substr(prefix_to_remove.size()); |
296 | 0 | } |
297 | 0 | return filepath; |
298 | 0 | } |
299 | | |
300 | | std::string ConCatPathFileName(const std::string& path, |
301 | 0 | const std::string& filename) { |
302 | 0 | std::string filepath = path; |
303 | 0 | if (filepath.length()) { |
304 | 0 | char& filepath_last_character = filepath.back(); |
305 | 0 | if (filepath_last_character == kPathSeparatorWindows) { |
306 | 0 | filepath_last_character = kPathSeparator; |
307 | 0 | } else if (filepath_last_character != kPathSeparator) { |
308 | 0 | filepath += kPathSeparator; |
309 | 0 | } |
310 | 0 | } |
311 | 0 | filepath += filename; |
312 | | // Ignore './' at the start of filepath. |
313 | 0 | if (filepath[0] == '.' && filepath[1] == kPathSeparator) { |
314 | 0 | filepath.erase(0, 2); |
315 | 0 | } |
316 | 0 | return filepath; |
317 | 0 | } |
318 | | |
319 | 0 | std::string PosixPath(const char* path) { |
320 | 0 | std::string p = path; |
321 | 0 | std::replace(p.begin(), p.end(), '\\', '/'); |
322 | 0 | return p; |
323 | 0 | } |
324 | 0 | std::string PosixPath(const std::string& path) { |
325 | 0 | return PosixPath(path.c_str()); |
326 | 0 | } |
327 | | |
328 | 0 | void EnsureDirExists(const std::string& filepath) { |
329 | 0 | auto parent = StripFileName(filepath); |
330 | 0 | if (parent.length()) EnsureDirExists(parent); |
331 | | // clang-format off |
332 | |
|
333 | | #ifdef _WIN32 |
334 | | (void)_mkdir(filepath.c_str()); |
335 | | #else |
336 | 0 | mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP); |
337 | 0 | #endif |
338 | | // clang-format on |
339 | 0 | } |
340 | | |
341 | | std::string FilePath(const std::string& project, const std::string& filePath, |
342 | 0 | bool absolute) { |
343 | 0 | return (absolute) ? AbsolutePath(filePath) |
344 | 0 | : RelativeToRootPath(project, filePath); |
345 | 0 | } |
346 | | |
347 | 0 | std::string AbsolutePath(const std::string& filepath) { |
348 | | // clang-format off |
349 | |
|
350 | | #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION |
351 | | return filepath; |
352 | | #else |
353 | | #if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__) |
354 | | char abs_path[MAX_PATH]; |
355 | | return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr) |
356 | | #else |
357 | 0 | char *abs_path_temp = realpath(filepath.c_str(), nullptr); |
358 | 0 | bool success = abs_path_temp != nullptr; |
359 | 0 | std::string abs_path; |
360 | 0 | if(success) { |
361 | 0 | abs_path = abs_path_temp; |
362 | 0 | free(abs_path_temp); |
363 | 0 | } |
364 | 0 | return success |
365 | 0 | #endif |
366 | 0 | ? abs_path |
367 | 0 | : filepath; |
368 | 0 | #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION |
369 | | // clang-format on |
370 | 0 | } |
371 | | |
372 | | std::string RelativeToRootPath(const std::string& project, |
373 | 0 | const std::string& filepath) { |
374 | 0 | std::string absolute_project = PosixPath(AbsolutePath(project)); |
375 | 0 | if (absolute_project.back() != '/') absolute_project += "/"; |
376 | 0 | std::string absolute_filepath = PosixPath(AbsolutePath(filepath)); |
377 | | |
378 | | // Find the first character where they disagree. |
379 | | // The previous directory is the lowest common ancestor; |
380 | 0 | const char* a = absolute_project.c_str(); |
381 | 0 | const char* b = absolute_filepath.c_str(); |
382 | 0 | size_t common_prefix_len = 0; |
383 | 0 | while (*a != '\0' && *b != '\0' && *a == *b) { |
384 | 0 | if (*a == '/') common_prefix_len = a - absolute_project.c_str(); |
385 | 0 | a++; |
386 | 0 | b++; |
387 | 0 | } |
388 | | // the number of ../ to prepend to b depends on the number of remaining |
389 | | // directories in A. |
390 | 0 | const char* suffix = absolute_project.c_str() + common_prefix_len; |
391 | 0 | size_t num_up = 0; |
392 | 0 | while (*suffix != '\0') |
393 | 0 | if (*suffix++ == '/') num_up++; |
394 | 0 | num_up--; // last one is known to be '/'. |
395 | 0 | std::string result = "//"; |
396 | 0 | for (size_t i = 0; i < num_up; i++) result += "../"; |
397 | 0 | result += absolute_filepath.substr(common_prefix_len + 1); |
398 | |
|
399 | 0 | return result; |
400 | 0 | } |
401 | | |
402 | | // Locale-independent code. |
403 | | #if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \ |
404 | | (FLATBUFFERS_LOCALE_INDEPENDENT > 0) |
405 | | |
406 | | // clang-format off |
407 | | // Allocate locale instance at startup of application. |
408 | | ClassicLocale ClassicLocale::instance_; |
409 | | |
410 | | #ifdef _MSC_VER |
411 | | ClassicLocale::ClassicLocale() |
412 | | : locale_(_create_locale(LC_ALL, "C")) {} |
413 | | ClassicLocale::~ClassicLocale() { _free_locale(locale_); } |
414 | | #else |
415 | | ClassicLocale::ClassicLocale() |
416 | 2 | : locale_(newlocale(LC_ALL, "C", nullptr)) {} |
417 | 0 | ClassicLocale::~ClassicLocale() { freelocale(locale_); } |
418 | | #endif |
419 | | // clang-format on |
420 | | |
421 | | #endif // !FLATBUFFERS_LOCALE_INDEPENDENT |
422 | | |
423 | 0 | std::string RemoveStringQuotes(const std::string& s) { |
424 | 0 | auto ch = *s.c_str(); |
425 | 0 | return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back())) |
426 | 0 | ? s.substr(1, s.length() - 2) |
427 | 0 | : s; |
428 | 0 | } |
429 | | |
430 | 0 | bool SetGlobalTestLocale(const char* locale_name, std::string* _value) { |
431 | 0 | const auto the_locale = setlocale(LC_ALL, locale_name); |
432 | 0 | if (!the_locale) return false; |
433 | 0 | if (_value) *_value = std::string(the_locale); |
434 | 0 | return true; |
435 | 0 | } |
436 | | |
437 | 0 | bool ReadEnvironmentVariable(const char* var_name, std::string* _value) { |
438 | | #ifdef _MSC_VER |
439 | | __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS |
440 | | #endif |
441 | 0 | auto env_str = std::getenv(var_name); |
442 | 0 | if (!env_str) return false; |
443 | 0 | if (_value) *_value = std::string(env_str); |
444 | 0 | return true; |
445 | 0 | } |
446 | | |
447 | | std::string ConvertCase(const std::string& input, Case output_case, |
448 | 0 | Case input_case) { |
449 | 0 | if (output_case == Case::kKeep) return input; |
450 | | // The output cases expect snake_case inputs, so if we don't have that input |
451 | | // format, try to convert to snake_case. |
452 | 0 | switch (input_case) { |
453 | 0 | case Case::kLowerCamel: |
454 | 0 | case Case::kUpperCamel: |
455 | 0 | return ConvertCase(CamelToSnake(input), output_case); |
456 | 0 | case Case::kDasher: |
457 | 0 | return ConvertCase(DasherToSnake(input), output_case); |
458 | 0 | case Case::kKeep: |
459 | 0 | printf("WARNING: Converting from kKeep case.\n"); |
460 | 0 | break; |
461 | 0 | default: |
462 | 0 | case Case::kSnake: |
463 | 0 | case Case::kScreamingSnake: |
464 | 0 | case Case::kAllLower: |
465 | 0 | case Case::kAllUpper: |
466 | 0 | break; |
467 | 0 | } |
468 | | |
469 | 0 | switch (output_case) { |
470 | 0 | case Case::kUpperCamel: |
471 | 0 | return ToCamelCase(input, true); |
472 | 0 | case Case::kLowerCamel: |
473 | 0 | return ToCamelCase(input, false); |
474 | 0 | case Case::kSnake: |
475 | 0 | return input; |
476 | 0 | case Case::kScreamingSnake: |
477 | 0 | return ToSnakeCase(input, true); |
478 | 0 | case Case::kAllUpper: |
479 | 0 | return ToAll(input, CharToUpper); |
480 | 0 | case Case::kAllLower: |
481 | 0 | return ToAll(input, CharToLower); |
482 | 0 | case Case::kDasher: |
483 | 0 | return ToDasher(input); |
484 | 0 | case Case::kSnake2: |
485 | 0 | return SnakeToSnake2(input); |
486 | 0 | default: |
487 | 0 | case Case::kUnknown: |
488 | 0 | return input; |
489 | 0 | } |
490 | 0 | } |
491 | | |
492 | | } // namespace flatbuffers |