// // mapped_file.cpp // conceal // // Created by Bob Polis at 2020-01-06 // Copyright (c) 2020 SwiftCoder. All rights reserved. // #include "libscio.hpp" #include #include #include #include #include #include #include #include using namespace sc::io; mapped_file::mapped_file(const std::string& path) { open(path); } mapped_file::~mapped_file() { if (_mapping) { munmap(_mapping, _length); _mapping = nullptr; _length = 0; } if (_fd != -1) { close(_fd); _fd = -1; } } mapped_file::mapped_file(mapped_file&& other) { _fd = other._fd; _mapping = other._mapping; _length = other._length; other._fd = -1; other._mapping = nullptr; other._length = 0; } mapped_file& mapped_file::operator=(mapped_file &&other) { if (&other != this) { mapped_file mf {std::move(other)}; std::swap(mf, *this); } return *this; } void mapped_file::open(const std::string& path) { if (_fd != -1) throw std::runtime_error("already open"); _fd = ::open(path.c_str(), O_RDONLY); throw_if_min1_msg(_fd, "could not open file"); struct stat st; throw_if_min1_msg(fstat(_fd, &st), "could not stat file"); _length = st.st_size; _mapping = reinterpret_cast(mmap(nullptr, _length, PROT_READ, MAP_PRIVATE, _fd, 0)); if (_mapping == MAP_FAILED) throw std::runtime_error("could not map file"); }