Merge pull request #3832 from mikkelfj/c_docs
[platform/upstream/flatbuffers.git] / src / util.cpp
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 #include "flatbuffers/util.h"
18
19 namespace flatbuffers {
20
21 bool FileExistsRaw(const char *name) {
22   std::ifstream ifs(name);
23   return ifs.good();
24 }
25
26 bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
27   std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
28   if (!ifs.is_open()) return false;
29   if (binary) {
30     // The fastest way to read a file into a string.
31     ifs.seekg(0, std::ios::end);
32     (*buf).resize(static_cast<size_t>(ifs.tellg()));
33     ifs.seekg(0, std::ios::beg);
34     ifs.read(&(*buf)[0], (*buf).size());
35   } else {
36     // This is slower, but works correctly on all platforms for text files.
37     std::ostringstream oss;
38     oss << ifs.rdbuf();
39     *buf = oss.str();
40   }
41   return !ifs.bad();
42 }
43
44 static LoadFileFunction g_load_file_function = LoadFileRaw;
45 static FileExistsFunction g_file_exists_function = FileExistsRaw;
46
47 bool LoadFile(const char *name, bool binary, std::string *buf) {
48   assert(g_load_file_function);
49   return g_load_file_function(name, binary, buf);
50 }
51
52 bool FileExists(const char *name) {
53   assert(g_file_exists_function);
54   return g_file_exists_function(name);
55 }
56
57 LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
58   LoadFileFunction previous_function = g_load_file_function;
59   g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
60   return previous_function;
61 }
62
63 FileExistsFunction SetFileExistsFunction(
64     FileExistsFunction file_exists_function) {
65   FileExistsFunction previous_function = g_file_exists_function;
66   g_file_exists_function = file_exists_function ?
67       file_exists_function : FileExistsRaw;
68   return previous_function;
69 }
70
71 }  // namespace flatbuffers