22 #include <boost/filesystem/path.hpp>
23 #include <boost/iostreams/stream.hpp>
29 typedef boost::iostreams::stream<boost::iostreams::mapped_file_source> MappedStream;
32 NdArray<T>
mmapNpy(
const boost::filesystem::path&
path, boost::iostreams::mapped_file_base::mapmode mode,
35 size_t n_elements = 0;
39 boost::iostreams::mapped_file_params map_params;
40 map_params.path = path.native();
41 map_params.flags = mode;
42 max_size =
std::max(max_size, boost::filesystem::file_size(path));
43 map_params.length = max_size;
45 boost::iostreams::mapped_file input(map_params);
46 MappedStream stream(input.operator boost::iostreams::mapped_file_source&());
47 stream.set_auto_close(
false);
50 if (dtype != NpyDtype<T>::str)
54 n_elements *= attrs.
size();
58 std::move(MappedContainer<T>(path, stream.tellg(), n_elements, attrs,
std::move(input), max_size))};
66 writeNpyHeader<T>(header, appendAttrShape(shape, attrs.
size()), attrs);
67 auto header_str = header.str();
68 auto header_size = header_str.size();
70 assert(header_size % 64 == 0);
75 n_elements *= attrs.
size();
76 size_t data_size = n_elements *
sizeof(T);
77 size_t total_size = header_size + data_size;
79 boost::iostreams::mapped_file_params map_params;
80 map_params.path = path.native();
81 map_params.flags = boost::iostreams::mapped_file_base::readwrite;
82 map_params.new_file_size = total_size;
83 if (max_size >= total_size)
84 map_params.
length = max_size;
86 max_size = total_size;
88 boost::iostreams::mapped_file output(map_params);
89 std::copy(header_str.begin(), header_str.end(), output.begin());
91 std::move(MappedContainer<T>(path, header_size, n_elements, attrs,
std::move(output), max_size))};
97 #endif // NPYMMAP_IMPL
void readNpyHeader(std::istream &input, std::string &dtype, std::vector< size_t > &shape, std::vector< std::string > &attrs, size_t &n_elements)
NdArray< T > mmapNpy(const boost::filesystem::path &path, boost::iostreams::mapped_file_base::mapmode mode=boost::iostreams::mapped_file_base::readwrite, size_t max_size=0)
NdArray< T > createMmapNpy(const boost::filesystem::path &path, const std::vector< size_t > &shape, const std::vector< std::string > &attr_names, size_t max_size=0)