forked from Project-OSRM/osrm-backend
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmmap_file.hpp
89 lines (79 loc) · 2.68 KB
/
mmap_file.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#ifndef OSRM_UTIL_MMAP_FILE_HPP
#define OSRM_UTIL_MMAP_FILE_HPP
#include "util/exception.hpp"
#include "util/exception_utils.hpp"
#include "util/vector_view.hpp"
#include <boost/filesystem/path.hpp>
#include <boost/iostreams/device/mapped_file.hpp>
namespace osrm
{
namespace util
{
namespace detail
{
template <typename T, typename MmapContainerT>
util::vector_view<T> mmapFile(const boost::filesystem::path &file, MmapContainerT &mmap_container)
{
try
{
mmap_container.open(file);
std::size_t num_objects = mmap_container.size() / sizeof(T);
auto data_ptr = mmap_container.data();
BOOST_ASSERT(reinterpret_cast<uintptr_t>(data_ptr) % alignof(T) == 0);
return util::vector_view<T>(reinterpret_cast<T *>(data_ptr), num_objects);
}
catch (const std::exception &exc)
{
throw exception(
boost::str(boost::format("File %1% mapping failed: %2%") % file % exc.what()) +
SOURCE_REF);
}
}
template <typename T, typename MmapContainerT>
util::vector_view<T> mmapFile(const boost::filesystem::path &file,
MmapContainerT &mmap_container,
const std::size_t size)
{
try
{
// Create a new file with the given size in bytes
boost::iostreams::mapped_file_params params;
params.path = file.string();
params.flags = boost::iostreams::mapped_file::readwrite;
params.new_file_size = size;
mmap_container.open(params);
std::size_t num_objects = size / sizeof(T);
auto data_ptr = mmap_container.data();
BOOST_ASSERT(reinterpret_cast<uintptr_t>(data_ptr) % alignof(T) == 0);
return util::vector_view<T>(reinterpret_cast<T *>(data_ptr), num_objects);
}
catch (const std::exception &exc)
{
throw exception(
boost::str(boost::format("File %1% mapping failed: %2%") % file % exc.what()) +
SOURCE_REF);
}
}
}
template <typename T>
util::vector_view<const T> mmapFile(const boost::filesystem::path &file,
boost::iostreams::mapped_file_source &mmap_container)
{
return detail::mmapFile<const T>(file, mmap_container);
}
template <typename T>
util::vector_view<T> mmapFile(const boost::filesystem::path &file,
boost::iostreams::mapped_file &mmap_container)
{
return detail::mmapFile<T>(file, mmap_container);
}
template <typename T>
util::vector_view<T> mmapFile(const boost::filesystem::path &file,
boost::iostreams::mapped_file &mmap_container,
std::size_t size)
{
return detail::mmapFile<T>(file, mmap_container, size);
}
}
}
#endif