2 * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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.
19 #include <cwrap/Fildes.h>
29 class MemoryMappedModel final : public ModelData
33 * @require fd and data SHOULD be valid
35 explicit MemoryMappedModel(int fd, void *data, size_t size) : _fd{fd}, _data{data}, _size{size}
48 MemoryMappedModel(const MemoryMappedModel &) = delete;
49 MemoryMappedModel(MemoryMappedModel &&) = delete;
52 const void *data(void) const override { return _data; };
53 const size_t size(void) const override { return _size; };
57 void *_data = nullptr;
63 std::unique_ptr<ModelData> load_modeldata(const std::string &path)
65 cwrap::Fildes fd(open(path.c_str(), O_RDONLY));
69 // Return nullptr on open failure
74 if (fstat(fd.get(), &st) == -1)
76 // Return nullptr on fstat failure
80 auto size = st.st_size;
81 auto data = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd.get(), 0);
83 if (data == MAP_FAILED)
85 // Return nullptr on mmap failure
89 return std::unique_ptr<ModelData>{new MemoryMappedModel(fd.release(), data, size)};