2 * Copyright 2016 Google Inc. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 // Dont't remove `format off`, it prevent reordering of win-includes.
20 # ifndef WIN32_LEAN_AND_MEAN
21 # define WIN32_LEAN_AND_MEAN
27 # include <windows.h> // Must be included before <direct.h>
30 # undef interface // This is also important because of reasons
36 #include "flatbuffers/base.h"
37 #include "flatbuffers/util.h"
43 namespace flatbuffers {
45 bool FileExistsRaw(const char *name) {
46 std::ifstream ifs(name);
50 bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
51 if (DirExists(name)) return false;
52 std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
53 if (!ifs.is_open()) return false;
55 // The fastest way to read a file into a string.
56 ifs.seekg(0, std::ios::end);
57 auto size = ifs.tellg();
58 (*buf).resize(static_cast<size_t>(size));
59 ifs.seekg(0, std::ios::beg);
60 ifs.read(&(*buf)[0], (*buf).size());
62 // This is slower, but works correctly on all platforms for text files.
63 std::ostringstream oss;
70 static LoadFileFunction g_load_file_function = LoadFileRaw;
71 static FileExistsFunction g_file_exists_function = FileExistsRaw;
73 bool LoadFile(const char *name, bool binary, std::string *buf) {
74 FLATBUFFERS_ASSERT(g_load_file_function);
75 return g_load_file_function(name, binary, buf);
78 bool FileExists(const char *name) {
79 FLATBUFFERS_ASSERT(g_file_exists_function);
80 return g_file_exists_function(name);
83 bool DirExists(const char *name) {
87 #define flatbuffers_stat _stat
88 #define FLATBUFFERS_S_IFDIR _S_IFDIR
90 #define flatbuffers_stat stat
91 #define FLATBUFFERS_S_IFDIR S_IFDIR
94 struct flatbuffers_stat file_info;
95 if (flatbuffers_stat(name, &file_info) != 0) return false;
96 return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
99 LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
100 LoadFileFunction previous_function = g_load_file_function;
101 g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
102 return previous_function;
105 FileExistsFunction SetFileExistsFunction(
106 FileExistsFunction file_exists_function) {
107 FileExistsFunction previous_function = g_file_exists_function;
108 g_file_exists_function =
109 file_exists_function ? file_exists_function : FileExistsRaw;
110 return previous_function;
113 bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
114 std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
115 if (!ofs.is_open()) return false;
120 // We internally store paths in posix format ('/'). Paths supplied
121 // by the user should go through PosixPath to ensure correct behavior
122 // on Windows when paths are string-compared.
124 static const char kPathSeparatorWindows = '\\';
125 static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
127 std::string StripExtension(const std::string &filepath) {
128 size_t i = filepath.find_last_of(".");
129 return i != std::string::npos ? filepath.substr(0, i) : filepath;
132 std::string GetExtension(const std::string &filepath) {
133 size_t i = filepath.find_last_of(".");
134 return i != std::string::npos ? filepath.substr(i + 1) : "";
137 std::string StripPath(const std::string &filepath) {
138 size_t i = filepath.find_last_of(PathSeparatorSet);
139 return i != std::string::npos ? filepath.substr(i + 1) : filepath;
142 std::string StripFileName(const std::string &filepath) {
143 size_t i = filepath.find_last_of(PathSeparatorSet);
144 return i != std::string::npos ? filepath.substr(0, i) : "";
147 std::string ConCatPathFileName(const std::string &path,
148 const std::string &filename) {
149 std::string filepath = path;
150 if (filepath.length()) {
151 char &filepath_last_character = string_back(filepath);
152 if (filepath_last_character == kPathSeparatorWindows) {
153 filepath_last_character = kPathSeparator;
154 } else if (filepath_last_character != kPathSeparator) {
155 filepath += kPathSeparator;
158 filepath += filename;
159 // Ignore './' at the start of filepath.
160 if (filepath[0] == '.' && filepath[1] == kPathSeparator) {
161 filepath.erase(0, 2);
166 std::string PosixPath(const char *path) {
167 std::string p = path;
168 std::replace(p.begin(), p.end(), '\\', '/');
172 void EnsureDirExists(const std::string &filepath) {
173 auto parent = StripFileName(filepath);
174 if (parent.length()) EnsureDirExists(parent);
178 (void)_mkdir(filepath.c_str());
180 mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
185 std::string AbsolutePath(const std::string &filepath) {
188 #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
192 char abs_path[MAX_PATH];
193 return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr)
195 char abs_path[PATH_MAX];
196 return realpath(filepath.c_str(), abs_path)
200 #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
204 // Locale-independent code.
205 #if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \
206 (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
209 // Allocate locale instance at startup of application.
210 ClassicLocale ClassicLocale::instance_;
213 ClassicLocale::ClassicLocale()
214 : locale_(_create_locale(LC_ALL, "C")) {}
215 ClassicLocale::~ClassicLocale() { _free_locale(locale_); }
217 ClassicLocale::ClassicLocale()
218 : locale_(newlocale(LC_ALL, "C", nullptr)) {}
219 ClassicLocale::~ClassicLocale() { freelocale(locale_); }
223 #endif // !FLATBUFFERS_LOCALE_INDEPENDENT
225 std::string RemoveStringQuotes(const std::string &s) {
226 auto ch = *s.c_str();
227 return ((s.size() >= 2) && (ch == '\"' || ch == '\'') &&
228 (ch == string_back(s)))
229 ? s.substr(1, s.length() - 2)
233 bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
234 const auto the_locale = setlocale(LC_ALL, locale_name);
235 if (!the_locale) return false;
236 if (_value) *_value = std::string(the_locale);
240 bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
242 __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS
244 auto env_str = std::getenv(var_name);
245 if (!env_str) return false;
246 if (_value) *_value = std::string(env_str);
250 void SetupDefaultCRTReportMode() {
254 // By default, send all reports to STDOUT to prevent CI hangs.
255 // Enable assert report box [Abort|Retry|Ignore] if a debugger is present.
256 const int dbg_mode = (_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG) |
257 (IsDebuggerPresent() ? _CRTDBG_MODE_WNDW : 0);
258 (void)dbg_mode; // release mode fix
259 // CrtDebug reports to _CRT_WARN channel.
260 _CrtSetReportMode(_CRT_WARN, dbg_mode);
261 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
262 // The assert from <assert.h> reports to _CRT_ERROR channel
263 _CrtSetReportMode(_CRT_ERROR, dbg_mode);
264 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
265 // Internal CRT assert channel?
266 _CrtSetReportMode(_CRT_ASSERT, dbg_mode);
267 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
273 } // namespace flatbuffers