Imported Upstream version 1.4.0
[platform/core/ml/nnfw.git] / compiler / circle2circle / src / Model.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 "Model.h"
18
19 #include <fstream>
20 #include <vector>
21
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <sys/stat.h>
25
26 namespace
27 {
28
29 class FileModel final : public luci::Model
30 {
31 public:
32   explicit FileModel(const std::string &filename) : _filename(filename) {}
33
34 public:
35   FileModel(const FileModel &) = delete;
36   FileModel(FileModel &&) = delete;
37
38 public:
39   const ::circle::Model *model(void) override
40   {
41     std::ifstream file(_filename, std::ios::binary | std::ios::in);
42     if (!file.good())
43       return nullptr;
44
45     file.unsetf(std::ios::skipws);
46
47     std::streampos fileSize;
48     file.seekg(0, std::ios::end);
49     fileSize = file.tellg();
50     file.seekg(0, std::ios::beg);
51
52     // reserve capacity
53     _data.reserve(fileSize);
54
55     // read the data
56     file.read(_data.data(), fileSize);
57     if (file.fail())
58       return nullptr;
59
60     return ::circle::GetModel(_data.data());
61   }
62
63 private:
64   const std::string _filename;
65   std::vector<char> _data;
66 };
67
68 } // namespace
69
70 namespace luci
71 {
72
73 std::unique_ptr<Model> load_model(const std::string &path)
74 {
75   return std::unique_ptr<Model>{new FileModel(path)};
76 }
77
78 } // namespace luci