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;
43 map_params.length = max_size;
45 max_size = boost::filesystem::file_size(path);
47 boost::iostreams::mapped_file input(map_params);
48 MappedStream stream(input.operator boost::iostreams::mapped_file_source&());
49 stream.set_auto_close(
false);
52 if (dtype != NpyDtype<T>::str)
56 n_elements *= attrs.
size();
60 std::move(MappedContainer<T>(path, stream.tellg(), n_elements, attrs,
std::move(input), max_size))};
68 writeNpyHeader<T>(header, appendAttrShape(shape, attrs.
size()), attrs);
69 auto header_str = header.str();
70 auto header_size = header_str.size();
72 assert(header_size % 64 == 0);
77 n_elements *= attrs.
size();
78 size_t data_size = n_elements *
sizeof(T);
79 size_t total_size = header_size + data_size;
81 boost::iostreams::mapped_file_params map_params;
82 map_params.path = path.native();
83 map_params.flags = boost::iostreams::mapped_file_base::readwrite;
84 map_params.new_file_size = total_size;
85 if (max_size >= total_size)
86 map_params.
length = max_size;
88 max_size = total_size;
90 boost::iostreams::mapped_file output(map_params);
91 std::copy(header_str.begin(), header_str.end(), output.begin());
93 std::move(MappedContainer<T>(path, header_size, n_elements, attrs,
std::move(output), max_size))};
99 #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)